在 C# 中覆盖现有文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/793589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:22:37  来源:igfitidea点击:

Overriding an existing file in C#

c#file

提问by

revised!

修改!

I want to create a file say called test.txt.

我想创建一个名为 test.txt 的文件。

if that file already exists I want to create file called test1.txt and so on.

如果该文件已经存在,我想创建名为 test1.txt 的文件等等。

回答by Samuel

Pass in FileMode.Createto File.Open(string, FileMode)when opening the file and it will create a new file every time.

通过在FileMode.CreateFile.Open(string, FileMode)打开文件时,它每次都会创建一个新的文件。

FileStream file = File.Open("text.txt", FileMode.Create);

回答by Andrew Hare

Here is a short example:

这是一个简短的例子:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        String file = "text.txt"; 

        if (File.Exists(file))
            File.Delete(file);

        FileStream fs = File.Create(file);
    }
}

回答by Erich Mirabal

The classes in System.IO should help you do that.

System.IO 中的类应该可以帮助您做到这一点。

FileStream fs = System.IO.File.Create(fileName);