繁体   English   中英

生成 txt 文件时出现“进程无法访问文件 --- 因为它正被另一个进程使用” C#

[英]"The process cannot access the file --- because it is being used by another process" when making txt file C#

string path = @$"c:\Users\asmet\Desktop\Database1/{username}";

if (File.Exists(path) == false)
{
    Console.WriteLine("Creating new file..");
    File.Create(path);
          
    // this is where the error is
    using (StreamWriter sw = new StreamWriter(path, true)) 
    {
        sw.WriteLine(DateTime.Now);
        sw.WriteLine($"rf = {rf}");
        sw.WriteLine($"pf = {pf}");
        sw.WriteLine($"sf = {sf}");
        sw.Close();
    }
}

我是 C# 的超级新手,我真的不知道我在做什么,但每当我尝试为安全的 rf、pf 和 sf 创建一个新文件时,它们都会崩溃。

这是在控制台应用程序的 VS Code 中。

用户名来自早期代码中的Console.ReadLine()

确切的错误信息:

System.IO.IOException:“进程无法访问文件 'c:\Users\asmet\Desktop\Database1\ausernameientered',因为它正被另一个进程使用。”

DataBase1只是一个文件夹

我试过查看与该问题相关的 forms,但经过一段时间的搜索后我从未找到解决方案,我希望代码在指定的位置创建一个新文件,然后将值放入文本文档,然后关闭它,所以我可以保存并稍后查看学校项目的数据。

发生的事情是每次我输入“用户名”并尝试创建一个新文件后它都会崩溃。

如果你取出:

        File.Create(path);

它可能会起作用。

StreamWriter(字符串,布尔值)
使用默认编码和缓冲区大小为指定文件初始化 StreamWriter class 的新实例。 如果文件存在,它可以被覆盖或追加。 如果该文件不存在,则此构造函数创建一个新文件

File.Create 打开一个文件 stream。你应该切换

using (StreamWriter sw = new StreamWriter(path, true)) **// this is where the error is**
{
    sw.WriteLine(DateTime.Now);
    sw.WriteLine($"rf = {rf}");
    sw.WriteLine($"pf = {pf}");
    sw.WriteLine($"sf = {sf}");
    sw.Close();
}

using (StreamWriter sw = File.Create(path)) **// this is where the error is**
{
    sw.WriteLine(DateTime.Now);
    sw.WriteLine($"rf = {rf}");
    sw.WriteLine($"pf = {pf}");
    sw.WriteLine($"sf = {sf}");
    sw.Close();
}

您不能同时打开 2 个文件流。

您可以使用File.WriteAllLines创建行并将行写入文件。 根据文档

创建一个新文件,将一个或多个字符串写入该文件,然后关闭该文件。 :

if (!File.Exists(path))
{
    Console.WriteLine("Creating new file...");

    File.WriteAllLines(path,
        new[]
        {
            DateTime.Now.ToString(),
            $"rf = {rf}",
            $"pf = {pf}",
            $"sf = {sf}"
        });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM