Search code examples
c#filelines

Lines form a file deleting on start C#


The problem im having is that everytime that i run my code, lines from the "Titles.txt" are getting deleted, and i don't know why. Basiclly, i run the program, then i write to the file with a textbox, then i close the program, check if it wrote to the file and it did, i run it again and check the file again and is empty. What can i do?

    public Form1()
    {
        InitializeComponent();

        if(!File.Exists(mainFolder))
        {
            Directory.CreateDirectory(mainFolder);
            Directory.CreateDirectory(tabTitlesFolder);
            var file = File.Create(tabTitles);
            file.Close();
        }
    }  

Solution

  • You need to check for the file, not the folder.

    public Form1()
    {
        InitializeComponent();
    
        if(!File.Exists(tabTitles)) // check if the file exists, (you had a check on mainFolder)
        {
            Directory.CreateDirectory(mainFolder);
            Directory.CreateDirectory(tabTitlesFolder);
            var file = File.Create(tabTitles); // this is what you are creating so also what you should be checking for above in the if
            file.Close();
        }
    } 
    

    Also File.Create will overwrite the file if it already exists, see the documentation.

    Finally types that implement IDisposable should be wrapped in a using block or a try/finally block to ensure they are released by the code even if an exception were to be thrown. File.Create returns FileStream which is disposable so it should be wrapped.

    using(File.Create(tabTitles)){}
    

    As you are not using the result you do not need to assign it to anything but you could if you wanted to write to the file.

    using(var file = File.Create(tabTitles)){
        // do something with file
    }