命名文本文件C# [英] naming the text file C#

查看:81
本文介绍了命名文本文件C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基于命令(控制台应用程序)我想创建一个文本文件并将其命名为用户输入的用户名,例如,如果用户输入用户名(Ali),将创建文本文件Ali.txt,我怎么能这样做





I am using Command-based (console application) I want to create a text file and name it as the user name entered by the user, for example if the user enter the user name (Ali) the text file will be created Ali.txt, how can I do that


Console.Write("Username: ");
                string Username = (Console.ReadLine());
                string fileName = Username+ ".txt";
                        string path = System.IO.Path.Combine(@"E:\\", fileName);
                         using (StreamWriter sw = File.CreateText(path))

推荐答案

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

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


看看这里:

如何:写入文本文件(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");
}


这篇关于命名文本文件C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆