使用c#创建并写入文本文件时出现问题

问题描述 投票:0回答:4

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

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

我在流编写器中遇到此异常:

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

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

c# file
4个回答
2
投票

创建

StreamWriter
对象时,您指定的是已作为
FileStream
打开的同一文件。

使用接受 StreamWriter

 对象的 
FileStream
 构造函数重载,而不是再次指定文件,如下所示:

using (StreamWriter sw = new StreamWriter(fs))
    

1
投票
我会简单地这样做:

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

请注意,我使用

Path.Combine

 作为创建路径的更好方法,并使用 File.WriteAllText
 作为创建文件并向其写入内容的简单方法。正如 MSDN 所说:

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

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


0
投票
using (TextWriter tw = new StreamWriter(path, true)) { tw.WriteLine("The next line!"); }
    

0
投票
问题可能是文件已打开或正在使用。考虑在写入之前检查文件是否打开:

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; }
    
© www.soinside.com 2019 - 2024. All rights reserved.