FileStream 一直说文件正忙,但根本没有任何应用程序打开它

发布于 2025-01-12 17:13:23 字数 3659 浏览 3 评论 0原文

我正在尝试创建一个程序,将某种数据写入 C# 中的文件。当我尝试运行代码时,控制台说文件正忙,即使我根本没有打开它。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace databaseProject
{
    public class Program
    {
        static void Main(string[] args)
        {
            Functions F = new Functions();

            string studentID;
            string studentName;
            string subjectA;
            string subjectB;


            Console.WriteLine("Please enter the student's ID.");
            studentID = Console.ReadLine();

            Console.WriteLine("Please enter the student's name.");
            studentName = Console.ReadLine();

            Console.WriteLine("Please enter the student's score for subject A");
            subjectA = Console.ReadLine();

            Console.WriteLine("Please enter the student's score for subject B");
            subjectB = Console.ReadLine();

            Functions.saveFile(studentID, studentName, subjectA, subjectB);
        }
    }

    public class Functions
    {


        public static void saveFile(string studentID, string studentName, string subjectA, string subjectB)
        {
            FileStream stream = new FileStream("DATA.txt", FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(stream);

            Console.WriteLine(studentID);
            Console.WriteLine(studentName);
            Console.WriteLine(subjectA);
            Console.WriteLine(subjectB);

            File.AppendAllText("DATA.txt", studentID + Environment.NewLine);
            File.AppendAllText("DATA.txt", studentName + Environment.NewLine);
            File.AppendAllText("DATA.txt", subjectA + Environment.NewLine);
            File.AppendAllText("DATA.txt", subjectB + Environment.NewLine);

            writer.Close();
            stream.Close();
        }
    }
}

控制台将

Unhandled exception. System.IO.IOException: The process cannot access the file 'C:\Users\User\Documents\codes\C#\databaseProjectCSlash\databaseProjectCSlash\bin\Debug\net6.0\DATA.txt' because it is being used by another process.
   at Microsoft.Win32.SafeHandles.SafeFileHandle.CreateFile(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options)
   at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize)
   at System.IO.Strategies.OSFileStreamStrategy..ctor(String path, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize)
   at System.IO.Strategies.FileStreamHelpers.ChooseStrategyCore(String path, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize)
   at System.IO.Strategies.FileStreamHelpers.ChooseStrategy(FileStream fileStream, String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, Int64 preallocationSize)
   at System.IO.StreamWriter.ValidateArgsAndOpenPath(String path, Boolean append, Encoding encoding, Int32 bufferSize)
   at System.IO.File.AppendAllText(String path, String contents)
   at databaseProject.Functions.saveFile(String studentID, String studentName, String subjectA, String subjectB) in C:\Users\User\Documents\codes\C#\databaseProjectCSlash\databaseProjectCSlash\Program.cs:line 52
   at databaseProject.Program.Main(String[] args) in C:\Users\User\Documents\codes\C#\databaseProjectCSlash\databaseProjectCSlash\Program.cs:line 34

在发送该消息后写入此内容,该文件将被擦除所有数据。

谢谢你的帮助,我真的很感激。

I am trying to create a program that writes some kind of data to a file in C#. when I tried running the code, the console said that the file is busy even though I am not opening it at all.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace databaseProject
{
    public class Program
    {
        static void Main(string[] args)
        {
            Functions F = new Functions();

            string studentID;
            string studentName;
            string subjectA;
            string subjectB;


            Console.WriteLine("Please enter the student's ID.");
            studentID = Console.ReadLine();

            Console.WriteLine("Please enter the student's name.");
            studentName = Console.ReadLine();

            Console.WriteLine("Please enter the student's score for subject A");
            subjectA = Console.ReadLine();

            Console.WriteLine("Please enter the student's score for subject B");
            subjectB = Console.ReadLine();

            Functions.saveFile(studentID, studentName, subjectA, subjectB);
        }
    }

    public class Functions
    {


        public static void saveFile(string studentID, string studentName, string subjectA, string subjectB)
        {
            FileStream stream = new FileStream("DATA.txt", FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(stream);

            Console.WriteLine(studentID);
            Console.WriteLine(studentName);
            Console.WriteLine(subjectA);
            Console.WriteLine(subjectB);

            File.AppendAllText("DATA.txt", studentID + Environment.NewLine);
            File.AppendAllText("DATA.txt", studentName + Environment.NewLine);
            File.AppendAllText("DATA.txt", subjectA + Environment.NewLine);
            File.AppendAllText("DATA.txt", subjectB + Environment.NewLine);

            writer.Close();
            stream.Close();
        }
    }
}

the console will write this instead

Unhandled exception. System.IO.IOException: The process cannot access the file 'C:\Users\User\Documents\codes\C#\databaseProjectCSlash\databaseProjectCSlash\bin\Debug\net6.0\DATA.txt' because it is being used by another process.
   at Microsoft.Win32.SafeHandles.SafeFileHandle.CreateFile(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options)
   at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize)
   at System.IO.Strategies.OSFileStreamStrategy..ctor(String path, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize)
   at System.IO.Strategies.FileStreamHelpers.ChooseStrategyCore(String path, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize)
   at System.IO.Strategies.FileStreamHelpers.ChooseStrategy(FileStream fileStream, String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, Int64 preallocationSize)
   at System.IO.StreamWriter.ValidateArgsAndOpenPath(String path, Boolean append, Encoding encoding, Int32 bufferSize)
   at System.IO.File.AppendAllText(String path, String contents)
   at databaseProject.Functions.saveFile(String studentID, String studentName, String subjectA, String subjectB) in C:\Users\User\Documents\codes\C#\databaseProjectCSlash\databaseProjectCSlash\Program.cs:line 52
   at databaseProject.Program.Main(String[] args) in C:\Users\User\Documents\codes\C#\databaseProjectCSlash\databaseProjectCSlash\Program.cs:line 34

after sending that message, the file would be wiped out of any data.

Thank you for your help, I really appreciate that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

灯角 2025-01-19 17:13:23

您的流程与自身发生冲突

您在这里打开它(顺便说一句,使用 File.CreateText 会更简单) - 但从未真正使用您创建的编写器:

FileStream stream = new FileStream("DATA.txt", FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(stream);

...那么您<即使 stream 已经打开,也尝试单独在此处附加它:

File.AppendAllText("DATA.txt", studentID + Environment.NewLine);

选择一种写入文件的方式,并坚持使用它。就我个人而言,我建议为您要写入的所有行创建一个 List 或数组,并且只需调用 File.WriteAllLines 一次,但是您可以继续使用编写器方法或File.AppendAllText方法...只是不能像这样一起使用。

下面是 saveFile 方法的更简单实现(已重命名以遵循正常的命名约定):

public static void SaveFile(string studentId, string studentName, string subjectA, string subjectB)
{
    var lines = new[] { studentId, studentName, subjectA, subjectB };
    // (Write the lines to the console here if you want.)
    File.WriteAllLines("DATA.txt", lines);
}

如果您想要追加数据而不是重新创建文件,只需使用 File.AppendAllLines 即可。

Your process is conflicting with itself.

You're opening it here (in a way that would be simpler with File.CreateText, by the way) - but never actually using the writer you've created:

FileStream stream = new FileStream("DATA.txt", FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(stream);

... then you're separately trying to append to it here, even though stream is already open:

File.AppendAllText("DATA.txt", studentID + Environment.NewLine);

Pick one way of writing to the file, and stick to it. Personally, I'd suggest creating a List<string> or an array for all the lines you want to write, and just call File.WriteAllLines once, but you could continue to use either the writer approach or the File.AppendAllText approach... just not together like this.

Here's a simpler implementation of your saveFile method (renamed to follow normal naming conventions):

public static void SaveFile(string studentId, string studentName, string subjectA, string subjectB)
{
    var lines = new[] { studentId, studentName, subjectA, subjectB };
    // (Write the lines to the console here if you want.)
    File.WriteAllLines("DATA.txt", lines);
}

If you want to append data instead of recreating the file, just use File.AppendAllLines instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文