如果用户输入的数据不存在,则创建.txt文件

时间:2015-07-21 15:07:29

标签: c# forms

有没有办法使用来自表单中输入的数据的名称来创建文本文件?

string path = @"E:\AppServ\**Example**.txt";
if (!File.Exists(path))
{
    File.Create(path);
}

**Example**是从用户输入的数据中取出的部分。

与此Console.Writeline("{0}", userData);

类似

1 个答案:

答案 0 :(得分:0)

以下是如何将文件存储到Windows上的登录用户My Documents文件夹中的示例。

您可以修改AppendUserFile函数以支持其他文件模式。如果存在,则此版本将打开Appending文件,如果不存在则创建它。

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;
                }
            }
        }
    }
}