Totallama Totallama - 27 days ago 14
C# Question

c# - How to create a file if it doesn't exist yet and add new text?

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
.

MMK MMK
Answer

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;

            }

        }
Comments