我正在做一個代碼,我有一個文本文件,其中包含10000多行唯一鍵(每個鍵在一個新行中)。我需要將密鑰與我提供的ProductID和ProductFeatures一起插入表中。StreamReader和StreamWriter在C語言中的while循環中嵌套#
我已經實現了這一點,通過使用下面的代碼來檢查表中已經存在的鍵並減少鍵的冗餘(表中沒有鍵兩次提供鍵)。
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的嵌套。最後,我必須刪除剛剛插入表格的行。
由於提前,
Viknesh
爲什麼你需要在循環中「刪除」該行,如果你只是根據插入的鍵在最後重寫文件,它會不會更有效,更不容易出錯?順便說一句,你應該通過使用'using'語句來將連接放置在方法中,如果這是ASP.NET的話,這一切都是最重要的。 –