进程无法访问文件';R:\mft classes\c#basical\c#net apps\employee info\fileList.txt';因为它正被另一个进程使用

进程无法访问文件';R:\mft classes\c#basical\c#net apps\employee info\fileList.txt';因为它正被另一个进程使用,c#,C#,我试图在“fileList.txt”中写入一些文件名。该文件已创建,但当我尝试写入时,它会显示上面的错误。我该怎么办 string strFilePath; //the current path is : "R:\mft classes\c# fundamental\c#.net apps\employeeinfo\WindowsFormsApplication2\bin\Debug" strFilePath = Directory.GetCurrentDirectory(); strFile

我试图在“fileList.txt”中写入一些文件名。该文件已创建,但当我尝试写入时,它会显示上面的错误。我该怎么办

string strFilePath;
//the current path is : "R:\mft classes\c# fundamental\c#.net apps\employeeinfo\WindowsFormsApplication2\bin\Debug"

strFilePath = Directory.GetCurrentDirectory();
strFilePath = Directory.GetParent(strFilePath).ToString();
strFilePath = Directory.GetParent(strFilePath).ToString();
strFilePath = Directory.GetParent(strFilePath).ToString();
strFilePath = strFilePath + "\\fileList.txt";
File.Create(strFilePath);
foreach (string saveMe in listBox1.Items)
{
File.WriteAllText(strFilePath, saveMe);
}

改用流编写器

string strFilePath;
//the current path is : "R:\mft classes\c# fundamental\c#.net apps\employeeinfo\WindowsFormsApplication2\bin\Debug"

strFilePath = Directory.GetCurrentDirectory();
strFilePath = strFilePath + "\\fileList.txt";

using (StreamWriter sw = new StreamWriter(strFilePath, true))
{
    foreach (string saveMe in listBox1.Items)
    {
        sw.Write(saveMe);
    }
}

问题正是错误所说的。如果在任何其他程序(例如文本编辑器,如记事本或Word)中打开了该文件,请在运行代码之前将其关闭

在运行程序之前,请关闭
fileList.txt
。的可能重复(完全相同的错误)。顺便说一句,WriteAllText不会追加。代码提示:使用Path.Combine(),而不是strFilePath+“\\fileList.txt”。调用File.Create创建文件并打开它。这个电话是没有必要的。如果文件不存在,
File.WriteAllText
方法将创建该文件。但是,每次都会覆盖文件。这是他自己的代码,使文件保持打开状态。此外,记事本不会像那样打开文件。