C# 使用c在文本文件中创建和写入时出现的问题#

C# 使用c在文本文件中创建和写入时出现的问题#,c#,file,C#,File,我尝试创建一个文本文件并向其中写入一些数据。我正在使用以下代码: public void AddNews(string path,string News_Title,string New_Desc) { FileStream fs = null; string fileloc = path + News_Title+".txt"; if (!File.Exists(fileloc)) { using (fs = new FileStream(fil

我尝试创建一个文本文件并向其中写入一些数据。我正在使用以下代码:

public void AddNews(string path,string News_Title,string New_Desc)
{
    FileStream fs = null;
    string fileloc = path + News_Title+".txt";
    if (!File.Exists(fileloc))
    {
        using (fs = new FileStream(fileloc,FileMode.OpenOrCreate,FileAccess.Write))
        {               
            using (StreamWriter sw = new StreamWriter(fileloc))
            {
                sw.Write(New_Desc);           
            }
        }
    }
}
我在stream writer中遇到此异常:

The process cannot access the file '..............\Pro\Content\News\AllNews\Par.txt'
because it is being used by another process.

文本文件已创建,但无法写入。

创建
StreamWriter
对象时,指定的文件与已作为
文件流打开的文件相同

使用接受
FileStream
对象的,而不是再次指定文件,如下所示:

using (StreamWriter sw = new StreamWriter(fs))

问题可能是文件已打开或正在使用。考虑在写入文件之前检查文件是否打开…< /P>
public bool IsFileOpen(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        // Is Open
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //Not Open
    return false;
}

祝你好运

我只想这样做:

public void AddNews(string path, string News_Title, string New_Desc)
{
    string fileloc = Path.Combine(path, News_Title+".txt");
    if (!File.Exists(fileloc)) {
        File.WriteAllText(fileloc, New_Desc);           
    }
}
请注意,我使用它作为创建路径的更好方法,以及创建文件并向其中写入内容的简单方法。正如MSDN所说:

如果目标文件已存在,则会覆盖该文件


因此,我们首先检查文件是否已经存在,就像您所做的那样。如果要覆盖其内容,请不要直接检查和写入。

为什么不使用File.writealText?
using (TextWriter tw = new StreamWriter(path, true))
{
  tw.WriteLine("The next line!");
}