且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

命名文本文件C#

更新时间:2023-02-20 11:30:37

请阅读该问题的所有评论。

为什么我建议更改 @E:\\ @ E:\?请参阅: 2.4.4.5字符串文字 [ ^ ]


看看这里:

如何:写入文本文件(C#编程指南) [ ^ ]

如何:将文本写入文件 [ ^ ]



Please, read all comments to the question.
Why do i recommend to change @"E:\\" to @"E:\"? Please, see: 2.4.4.5 String literals[^]

Have a look here:
How to: Write to a Text File (C# Programming Guide)[^]
How to: Write Text to a File[^]

Console.Write("Enter username: ");
string Username = Console.ReadLine();
//here you should check if UserName is not null or empty!
string fileName = Username+ ".txt";
string path = System.IO.Path.Combine(@"E:\", fileName);
using (StreamWriter sw = new StreamWriter(path))
{
        sw.WriteLine(Username);
}


添加到Maciej在这里显示的内容:



那里有几种方法可以创建空白文件可以在C#中创建:



1.
To add to what Maciej has shown you here:

There are several ways to create a "blank" File can be created in C#:

1.
File.Create(pathName); // will leave the created File open

因为文件保持打开通常是不希望:

Since leaving the File open is often not desired:

using (File.Create(pathName))
using (File.Create(pathName)) {}
File.Create(pathName).Close();
File.Create(pathName).Dispose();

2。要将内容写入文件,如果文件不存在则自动创建文件:



请参阅Maciej的答案......以及...研究各种作家 可在System.IO库中找到:TextWriter,XmlWriter,以及StreamWriter。

2. To write content to a file, with the file automatically created if it does not exist:

See Maciej's answer here ... and ... study the various "Writers" available in the System.IO library: TextWriter, XmlWriter, as well as StreamWriter.

File.WriteAllText(pathName, String.Empty);
File.CreateText(pathName).Close();

因为如果文件已经存在,你可能想要做一些不同的事情,这是一种典型的代码模式:

Since you may want to do something differently if a File already exists, this is a typical code pattern:

if (File.Exists(pathName))
{
   // whatever if file exists
   // for example 
   // File.AppendAllText(pathName, "text to append");
}
else
{
   // whatver if file does not exist
   // for example 
   // File.WriteAllText(pathName, "initial text");
}