2015-07-21 78 views
1

有沒有什麼方法使用來自表單中輸入數據的名稱來創建文本文件?如果用戶輸入的數據不存在,則創建一個.txt文件

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

**Example**正在從用戶輸入的數據所採取的一部分。

這個Console.Writeline("{0}", userData);

+3

看看'的String.format()' –

+0

你的意思在字符串中使用野生字符或實際星號?對於文件創建過程,您可以這樣做:'FileInfo file = new FileInfo(path);如果(!file.Exists && file.Directory.Exists){file.Create(); } else {//處理失敗}' – CalebB

+2

@MathiasBecher肯定'Path.Combine()'會更好? – stuartd

回答

0

這裏差不多是如何文件存儲在用戶的我的文檔在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; 
       } 
      } 
     } 
    } 
} 
+1

這是一個相當混亂的示例。請不要使用string.Concat來組合路徑和文件名,這就是Path.Combine的用途。 – stuartd

+0

我將它更新爲Environment.SpecialFolder和Path.Combine。應該注意的是,儘管path.combine基本上和string.concat做了同樣的事情,除了它確保你不會得到額外的\(路徑分離器)。 –

+1

我不知道你爲什麼要調用.Dispose()手動,當你可以把整個FileStream放入一個使用塊 – oscilatingcretin

相關問題