有没有什么方法使用来自表单中输入数据的名称来创建文本文件?如果用户输入的数据不存在,则创建一个.txt文件
string path = @"E:\AppServ\**Example**.txt";
if (!File.Exists(path))
{
File.Create(path);
}
**Example**
正在从用户输入的数据所采取的一部分。
这个Console.Writeline("{0}", userData);
有没有什么方法使用来自表单中输入数据的名称来创建文本文件?如果用户输入的数据不存在,则创建一个.txt文件
string path = @"E:\AppServ\**Example**.txt";
if (!File.Exists(path))
{
File.Create(path);
}
**Example**
正在从用户输入的数据所采取的一部分。
这个Console.Writeline("{0}", userData);
这里差不多是如何文件存储在用户的我的文档在Windows文件夹中登录的例子。
您可以修改AppendUserFile函数以支持其他文件模式。如果该版本存在,该版本将打开附加文件,或者如果该文件不存在,则创建该文件。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
AppendUserFile("example.txt", tw =>
{
tw.WriteLine("I am some new text!");
});
Console.ReadKey(true);
}
private static bool AppendUserFile(string fileName, Action<TextWriter> writer)
{
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string filePath = Path.Combine(path, fileName);
FileStream fs = null;
if (File.Exists(filePath))
fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read);
else
fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read);
using (fs)
{
try
{
TextWriter tw = (TextWriter)new StreamWriter(fs);
writer(tw);
tw.Flush();
return true;
}
catch
{
return false;
}
}
}
}
}
这是一个相当混乱的示例。请不要使用string.Concat来组合路径和文件名,这就是Path.Combine的用途。 – stuartd
我将它更新为Environment.SpecialFolder和Path.Combine。应该注意的是,尽管path.combine基本上和string.concat做了同样的事情,除了它确保你不会得到额外的\(路径分离器)。 –
我不知道你为什么要调用.Dispose()手动,当你可以把整个FileStream放入一个使用块 – oscilatingcretin
看看'的String.format()' –
你的意思在字符串中使用野生字符或实际星号?对于文件创建过程,您可以这样做:'FileInfo file = new FileInfo(path);如果(!file.Exists && file.Directory.Exists){file.Create(); } else {//处理失败}' – CalebB
@MathiasBecher肯定'Path.Combine()'会更好? – stuartd