|
|
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已! |
|
恭喜您是本站第 1729345
位訪客!
登入 | 註冊
|
|
|
|
發表者 |
討論內容 |
冷日 (冷日) |
發表時間:2014/10/9 9:28 |
- Webmaster

- 註冊日: 2008/2/19
- 來自:
- 發表數: 15771
|
- [轉貼]如何:將文字寫入檔案
- 如何:將文字寫入檔案
.NET Framework 4.5
下列範例將示範如何將文字寫入文字檔。 範例
第一個範例藉由搜尋會從使用者的我的文件資料夾中的所有文字檔 "*.txt"同步處理並將其寫入大型文字檔。 C#
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StringBuilder sb = new StringBuilder();
foreach (string txtName in Directory.EnumerateFiles(mydocpath,"*.txt"))
{
using (StreamReader sr = new StreamReader(txtName))
{
sb.AppendLine(txtName.ToString());
sb.AppendLine("= = = = = =");
sb.Append(sr.ReadToEnd());
sb.AppendLine();
sb.AppendLine();
}
}
using (StreamWriter outfile = new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
{
outfile.Write(sb.ToString());
}
}
}
下一個範例顯示如何以非同步方式從文字方塊中寫入使用者的輸入至檔案。 C#
using System;
using System.Text;
using System.Windows;
using System.IO;
namespace WpfApplication
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void AppendButton_Click(object sender, RoutedEventArgs e)
{
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StringBuilder sb = new StringBuilder();
sb.AppendLine("New User Input");
sb.AppendLine("= = = = = =");
sb.Append(UserInputTextBox.Text);
sb.AppendLine();
sb.AppendLine();
using (StreamWriter outfile = new StreamWriter(mydocpath + @"\UserInputFile.txt", true))
{
await outfile.WriteAsync(sb.ToString());
}
}
}
}
請參閱 工作 如何:列舉目錄和檔案 如何:讀取和寫入新建立的資料檔案 如何:開啟並附加至記錄檔 如何:從檔案讀取文字 如何:從字串中讀取字元 如何:將字元寫入至字串 參考 StreamWriter File.CreateText 其他資源 檔案和資料流 I/O
原文出處:如何:將文字寫入檔案
|
|
討論串
|