c# - 如果文件不存在如何创建文件并添加新文本?

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

如果文件不存在,我的代码可以正常创建文件并插入新文本,或者如果文件已经存在,它会重写当前内容。

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();

现在我需要对其进行更改,使其不再重写内容,而是将新文本添加到以前的内容中。 其次,我需要知道文件是否完全为空,在这种情况下插入 textA 或者如果已经有一些内容,在这种情况下添加 textB.

您可以尝试类似的方法:

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;

        }
    }

你快到了!神奇的词是 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));
    }
}

您不需要将 sw.Close();using(StreamWriter){} 块结合使用,因为流将自动关闭,但它确实提高了开始时的可读性。

此外,当 StreamWriter 关闭时,它会同时自动 Dispose()(见下面的代码片段),因此不需要自己调用 Dispose()。

public override void Close()
{
    this.Dispose(true);
    GC.SuppressFinalize(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;

            }

        }

有一种更简单的做事方式(正如 Equalsk 评论的那样),使用 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);
}