我有文本文件。我正在阅读文本文档并将其拆分为一个数组。我尝试删除空白。所以我将数组的元素移动到字符串列表中。
这里部分代码
List<string> words =new List<string>();
string allcomments = File.ReadAllText("D:\\all comment.txt");//read text flile
string[] tc = allcomments.Split(' '); //split contains of text flie into tokens
foreach (string t in tc)
{
string token = t;
token = token.Trim();//to remove white spaces
words.Add(token);
}
//save list of words in the database
SqlConnection connection = new SqlConnection("Server=DESKTOP-JRS3DQ4; DataBase=My_Project; Integrated Security=true");
connection.Open();
SqlCommand command = new SqlCommand("INSERT INTO tokens_all_comments (tokens) VALUES (@tokens)", connection);
command.Parameters.Add("@tokens", SqlDbType.NVarChar, 250); //size and type must match your DB
foreach(var w in words)
{
command.Parameters["@tokens"].Value = _words[w];
command.ExecuteNonQuery();
}
connection.Close();
当我尝试运行代码时,出现以下错误
错误 3 当前上下文中不存在名称“_words”
我该如何修复代码?
在这里:
foreach(var w in words)
{
command.Parameters["@tokens"].Value = _words[w];
command.ExecuteNonQuery();
}
您正在尝试使用_words
未在任何地方声明的内容。这是一个错字,我相信你想使用words
(没有下划线)。
您已经在循环 中的单词foreach
,因此您不必words
作为数组访问,而是直接访问w
在 foreach 中声明的变量。此外,目前您只会将最后一个单词作为 sql 参数,因为您没有连接它们的值,它总是被分配。
您可以在不foreach
使用 using 的情况下连接所有单词String.Join()
:
command.Parameters["@tokens"].Value = String.Join("", words.ToArray());
您还可以省略所有 split 和 foreach 并使用简单的直接删除所有空格replace()
:
command.Parameters["@tokens"].Value = allcomments.Replace(" ", "");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句