【发布时间】:2012-08-29 09:40:35
【问题描述】:
我正在编写一个代码,其中我有一个文本文件,其中包含 10000 多行唯一键(每个键在一个新行中)。我需要将密钥与我提供的 ProductID 和 ProductFeatures 一起插入到表中。
我通过使用以下代码来实现这一点,该代码检查表中已经存在的键并减少键的冗余(表中没有键会出现两次)。
public void reader(string productid,string productfeature)
{
con.Open();
using (StreamReader sr = new StreamReader(Server.MapPath("keys.txt")))
{
while(sr.Peek() >=0)
{
string str = sr.ReadLine();
SqlCommand cmd = new SqlCommand("select count(newkey) from serialkey where newkey ='"+str.ToString()+"'", con);
int keyvalue = Convert.ToInt32(cmd.ExecuteScalar());
if (keyvalue == 0)
{
com = new SqlCommand("insert into SerialKey (productid,productfeatures,newkey) values ('" + productid.ToString() + "','" + productfeature.ToString() + "','" + key + "')", con);
com.ExecuteNonQuery();
}
}
}
con.Close();
}
这段代码对我来说绝对没问题,但是我决定在这个过程中做一些修改。
- 只要将键插入表中,就应该从文本文件中删除键(行)。
为此,我想我必须在同一个 while 循环中使用 StreamWriter/Textwriter,所以我尝试使用此代码。
using (StreamReader sr = new StreamReader(Server.MapPath("keys.txt")))
{
while (sr.Peek() >= 0)
{
string str = sr.ReadLine();
SqlCommand cmd = new SqlCommand("select count(newkey) from serialkey where newkey ='" + str.ToString() + "'", con);
int keyvalue = Convert.ToInt32(cmd.ExecuteScalar());
if (keyvalue == 0)
{
string line = null;
sr.Close();
TextWriter writer = new StreamWriter(Server.MapPath("keys.txt"), true);
if (insert(productid, productfeature, str))
{
if (str != null)
{
writer.WriteLine(line);
}
writer.Flush();
writer.Close();
}
}
}
}
我认为我使用了正确的逻辑来删除已插入的行。 如果我保留这行代码
sr.Close();
我收到以下错误
“无法从关闭的 TextReader 中读取。”
如果我删除该行
sr.Close();
我得到了错误
"进程无法访问文件'myfolderpath\keys.txt',因为它 正在被另一个进程使用。”
我可以在 whileloop 中使用 StreamReader 和 StreamWriter 的嵌套吗?最后,我必须删除刚刚插入到表中的行。
提前致谢,
维克内什
【问题讨论】:
-
为什么需要在循环中“删除”该行,如果您只是根据插入的键在末尾重写文件,它会不会更有效并且更不容易出错?顺便说一句,你应该使用
using-statement 来处理方法中的连接,如果这是 ASP.NET 的话。
标签: c# streamreader streamwriter