StreamWriter cannot be disposed

59 views Asked by At

I just create a class named WriteLog,this class contains the following methods:

    <!-- language: c# -->
    //First Version:
    public void Add(string location, string words)
    {
        StreamWriter sw = new StreamWriter(location);
        sw.WriteLine(words);
        sw.Close()
    }
    //Using Version:
    public void Add(string location, string words)
    {
        using (StreamWriter sw = File.AppendText(location))
        {
            sw.WriteLine(words);
        }
    }
    //My file path:
    string test = Path.GetDirectoryName(path) + "\\" + DateTime.Now.ToString("yyyyMMddHHmmssff") + ".json";
    //Where the Exception throwed:
    WriteLog.Add(ltn, time);  
    //Code..  
    File.Delete(ltn);  

But,there was a problem when I called it this way:
it throwed IOException:
This file is in use by another process and cannot be accessed by that process.
Even using cannot solve the problem.
I have verified that:
1.I comment out this code(WriteLog.Add),and Exception wasn't throwed again.
2.My file path is OK,and my application can access the path.
3.No Inner Exceptions.
I also tried Close, Dispose and Flush,and even tried to use them at a time,but it doesn't work.
Who have a solution?

PS:I'm a Chinese,so my grammar probably isn't OK.Sincere apology.

0

There are 0 answers