Here is my program:
protected int CheckExisting(string item_id)
{
StreamReader sr = new StreamReader(@"D:\ItemID.txt");
string line = sr.ReadLine();
while (line != null)
{
if (0 == string.Compare(line, item_id))
return 1;
line = sr.ReadLine();
}
sr.Close();
return 0;
}
protected void WriteNewLog(string item_id)
{
using (StreamWriter sw = File.AppendText(@"D:\ItemID.txt"))
{
sw.WriteLine(item_id);
}
}
protected void xHandler(int num)
{
for(int i= 0; i< num; i++)
if (0 == CheckExisting(item_id))
{
WriteNewLog(item_id);
}
}
When o run the program, an exception unhandled occur: “The process cannot access the file ‘D:\ItemID.txt’ because it is being used by another process.” Can u guys help me fix that? Thanks so much!
If this executes:
then you won’t close your
StreamReader. Use ausingblock when reading as well as writing.Additionally:
boolinstead of an integer to indicate yes/no resultsCompareand checking the results against0File.ReadLinesis a simpler way of reading linesCheckExistingto start withxHandlerdoesn’t follow .NET naming conventionsCheckExistingandWriteNewLogmethods need to be protected rather than privateivariable inxHandlerHere’s the implementation I’d use: