Proper way of waiting until a file is created

前端 未结 2 628
日久生厌
日久生厌 2021-01-21 18:51

I have the following code:

// get location where application data director is located
var appData = Environment.GetFolderPath(Environment.SpecialFolder.Applicati         


        
相关标签:
2条回答
  • 2021-01-21 19:08

    The reason for that is because File.Create is declared as:

    public static FileStream Create(
        string path
    )
    

    It returns a FileStream. The method is supposed to be used to create and open a file for writing. Since you never dispose of the returned FileStream object you're basically placing your bets on the garbage collector to collect that object before you need to rewrite the file.

    So, to fix the problem with the naive solution you should dispose of that object:

    System.IO.File.Create(file).Dispose();
    

    Now, the gotcha here is that File.AppendAllText will in fact create the file if it does not exist so you don't even need that code, here is your full code with the unnecessary code removed:

    // get location where application data director is located
    var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    
    // create dir if it doesnt exist
    var folder = System.IO.Path.Combine(appData, "SomeDir");
    System.IO.Directory.CreateDirectory(folder);
    
    // write something to the file
    var file = System.IO.Path.Combine(folder, "test.txt");
    System.IO.File.AppendAllText(file,"Foo");
    

    Directory.CreateDirectory will likewise not crash if the folder already exists so you can safely just call it.

    0 讨论(0)
  • 2021-01-21 19:17

    There is no need to create the file if you intend to use File.AppendAllText

    About the root cause for the error, and a preferred way to write to files in general:

    The file was created, and returned a stream that you didn't use/close. best method should be to use this stream to write to the file.

    using (FileStream fs = File.Create(file))
    {
         fs.Write("What ever you need to write..");
    }
    
    0 讨论(0)
提交回复
热议问题