茫茫網海中的冷日 - 對這文章發表回應
茫茫網海中的冷日
         
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已!
 恭喜您是本站第 1729349 位訪客!  登入  | 註冊
主選單

Google 自訂搜尋

Goole 廣告

隨機相片
IMG_0244.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

對這文章發表回應

發表限制: 非會員 可以發表

發表者: 冷日 發表時間: 2014/10/9 9:28:20
如何:將文字寫入檔案
.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

原文出處:如何:將文字寫入檔案
內容圖示
url email imgsrc image code quote
樣本
bold italic underline linethrough   












 [詳情...]
validation picture

注意事項:
預覽不需輸入認證碼,僅真正發送文章時才會檢查驗證碼。
認證碼有效期10分鐘,若輸入資料超過10分鐘,請您備份內容後,重新整理本頁並貼回您的內容,再輸入驗證碼送出。

選項

Powered by XOOPS 2.0 © 2001-2008 The XOOPS Project|