-2

My code works fine for creating a file if it doesn't exist and inserting new text, or if the file already exists, it rewrites the current contents.

path = @"C:\MY FOLDER\data.txt";

FileStream fileS = null;

bool done = false;

while (!done)
{
    done = true;

    try
    {
        FileStream fileStream = File.Open(path, FileMode.OpenOrCreate);
        fileStream.SetLength(0);
        fileStream.Close();
        fileS = File.OpenWrite(path);
    }
    catch (IOException ex)
    {
        done = false;
        // Thread.Sleep(3);
    }
}    

using (StreamWriter fs = new StreamWriter(fileS))
{
    fs.Write(textA);
    fs.Close();
};

fileS.Dispose();

Now I need to change it so it doesn't rewrites the contents anymore but instead add new text to the previous contents. Second, I need to know if the file is completely empty and in that case insert textA or if there is already some contents and in this case add textB.

diiN__________
  • 7,393
  • 6
  • 42
  • 69
Totallama
  • 418
  • 3
  • 10
  • 26
  • If this is just creating text files then `File.AppendAllText(path, text);` does all of this for you with no fuss. To check if the file is empty get its length in bytes, 0 is empty. – Equalsk Nov 08 '16 at 11:45
  • fileS = File.AppendAllText(path, textA); throws error: Cannot implicitly convert type 'void' to 'System.IO.FileStream' – Totallama Nov 08 '16 at 11:49
  • You can't just throw the code I suggested into the middle of your existing method and expect it to work. Go and read about the method and how to use it and implement it properly. – Equalsk Nov 08 '16 at 11:51

4 Answers4

1

Try this

        string path = @"Your File Path";

        bool done = false;

        while (!done)
        {
            done = true;

            try
            {
                FileStream fileStream = null;
                fileStream = File.Open(path, File.Exists(path) ? FileMode.Append : FileMode.OpenOrCreate);

                using (StreamWriter fs = new StreamWriter(fileStream))
                {
                    fs.WriteLine(fileStream.Length == 0 ? "Text A" : "Text B");
                };
                fileStream.Close();
            }
            catch (IOException)
            {
                done = false;

            }

        }
MMK
  • 3,673
  • 1
  • 22
  • 30
  • This is subject to race conditions. Rather use [`File.Open(path, FileMode.Append, FileAccess.Write)`](https://learn.microsoft.com/de-de/dotnet/api/system.io.file.open?view=netframework-4.8#System_IO_File_Open_System_String_System_IO_FileMode_System_IO_FileAccess_). – ComFreek Aug 21 '19 at 08:18
0

You could try something like that:

while (!done)
    {
        done = true;

        try
        {
            FileStream fileStream;
            if (File.Exists(path))
            {
                fileStream = File.Open(path, FileMode.Append);
            }
            else
            {
                fileStream = File.Open(path, FileMode.OpenOrCreate);
            }

            if (fileStream.Length == 0)
            {
                //write textA
            }
            else
            {
                //write textB
            }
            fileStream.Close();

        }
        catch (IOException ex)
        {
            done = false;

        }
    }
Isaak
  • 66
  • 2
0

You're nearly there! The magic word is AppendText(string)

var path = @"C:\MY FOLDER\data.txt";

//Create the file if it doesn't exist
if (!File.Exists(path)) 
{
    using (var sw = File.CreateText(path))
    {
        sw.WriteLine("Hello, I'm a new file!!");

        // You don't need this as the using statement will close automatically, but it does improve readability
        sw.Close();
    }
}

using (var sw = File.AppendText(path))
{
    for (int i = 0; i < 10; i++)
    {
        sw.WriteLine(string.Format("Line Number: {0}", i));
    }
}

You don't need to use sw.Close(); in conjunction with the using(StreamWriter){} block as the stream will be closed automatically, but it does improve readability starting off.

Also, when the StreamWriter is closed, it will automatically Dispose() at the same time (see code snippet below), so calling Dispose() yourself is unnecessary.

public override void Close()
{
    this.Dispose(true);
    GC.SuppressFinalize(this);
}
Neville
  • 413
  • 5
  • 6
  • But I need the while loop to be there as it was, it is crucial. And I need to check if the file is EMPTY! not if it was just created because the file can be empty later for various reasons.. – Totallama Nov 08 '16 at 12:08
  • Ah-ha I misunderstood! Then you can check if ``(new FileInfo(filename).Length == 0) {...}`` instead. A length of 0 means the file is empty. – Neville Nov 08 '16 at 12:45
0

There is a much simpler way of doing things (as Equalsk commented), with the File class.

File.AppendAllText(String, String) documentation

var path = @"C:\MY FOLDER\data.txt";        
var textA = "textA";    
var textB = "textB";

// Check if file exists
if (File.Exists(path))
{
    // Check if file is empty or not
    if (new FileInfo(path).Length == 0)
    {
        // If empty, write:
        File.AppendAllText(path, textA + Environment.NewLine);
    }
    else
    {
        // I not empty, write (appends text):
        File.AppendAllText(path, textB + Environment.NewLine);
    }
}
else
{
    // If file not exist, create it and write
    File.AppendAllText(path, textA + Environment.NewLine);
}
Jim
  • 2,974
  • 2
  • 19
  • 29