使用 C# 在文本文件中换行

New line in text file using C#

我是一名刚开始学习C#的学生,

我正在尝试使用文本文件创建注册和登录函数,并将用户输入的详细信息保存到文本文件中,但是当我再次 运行 我的函数时,它会重写已经存在的内容开始新的一行。

这是我的一些重要代码

using System;
using System.IO;

namespace SDD_Assessment_2
{
    class Program
    {
        static void Main(string[] args)
        {
            //Write();
            //GetTime();
            var privInfo = SignUp();
            var FullName = Profile(privInfo);
            Profile(privInfo);
            //Test(FullName);
        }
        const string filename = "Workout.txt";
        static string[] SignUp()
        {
            string[] privinfo = new string[4];

            Console.Write("First Name: ");
            privinfo[0] = Console.ReadLine();
            Console.Write("Last Name: ");
            privinfo[1] = Console.ReadLine();
            Console.Write("Email: ");
            privinfo[2] = Console.ReadLine();
            Console.Write("Password: ");
            privinfo[3] = Console.ReadLine();

            StreamWriter NewAccount = new StreamWriter(filename);
            //NewAccount.WriteLine(privinfo[0] + "," + privinfo[1] + "," + privinfo[2] + "," + privinfo[3] + Environment.NewLine);
            File.AppendAllText(filename, privinfo[0] + ", " + privinfo[1] + "," + privinfo[2] + "," + privinfo[3] + Environment.NewLine);
            NewAccount.Close();

            return privinfo;
        }
    }
}

当我 运行 现在,它说“System.IO.IOException:进程无法访问文件 'filename',因为它正被另一个进程使用。”

我试过了,有用

不使用时不要打开流

文件名包含目录

class Program
{
    static void Main(string[] args)
    {
        SignUp();
    }

    const string filename = "Workout.txt";
    static string[] SignUp()
    {
        string[] privinfo = new string[4];

        privinfo[0] = "First Name:";
        privinfo[1] = "Last Name: ";
        privinfo[2] = "Email: ";
        privinfo[3] = "Password: ";

        File.AppendAllText(Path.Combine(Environment.CurrentDirectory, filename), privinfo[0] + ", " + privinfo[1] + "," + privinfo[2] + "," + privinfo[3] + Environment.NewLine);

        return privinfo;
    }
}

运行 2 次

文件内容为

First Name:, Last Name: ,Email: ,Password: 
First Name:, Last Name: ,Email: ,Password: 

您的代码大部分是正确的。你需要改变

StreamWriter NewAccount = new StreamWriter(filename);
//NewAccount.WriteLine(privinfo[0] + "," + privinfo[1] + "," + privinfo[2] + "," + privinfo[3] + Environment.NewLine);
File.AppendAllText(filename, privinfo[0] + ", " + privinfo[1] + "," + privinfo[2] + "," + privinfo[3] + Environment.NewLine);
NewAccount.Close();

只是

File.AppendAllText(filename, privinfo[0] + ", " + privinfo[1] + "," + privinfo[2] + "," + privinfo[3] + Environment.NewLine);

您对 NewAccount 的分配会打开文件流,从而使文件句柄保持打开状态。这意味着您的 File.AppendAllText 无法完成,因为该文件之前是在非共享模式下打开的。

如果您删除了 File.AppendAllText,您将不会收到错误,但您最终会得到一个零字节文件,因为您没有向流中写入任何内容。

因为您根本没有使用 NewAccount,删除这些行将允许 File.AppendAllText 无误地完成,并且...附加您期望的所有文本,这将是值名字和姓氏、电子邮件和密码。