目前知道的有:

  • System.IO.StreamWriter
  • System.IO.File.WriteAllLines
  • System.IO.File.WriteAllText
  • System.IO.File.CreateText

System.IO.StreamWriter:

    // 使用'using' 自動做Flush()、Close()、Dispose(), 釋放tw資源.
    using ( StreamWriter tw = new StreamWriter( "test.txt", true ) )  // 'true':新建或附加.
    {
        tw.WriteLine( "The next line!" );
    }

    using ( StreamWriter tw = new StreamWriter( "test.txt", false ) )  // 'false',或沒填:新建或覆蓋.
    {
        tw.WriteLine( "The next line!" );
    }

參考:Create a .txt file if doesn't exist, and if it does append a new line

 

System.IO.StreamWriter、System.IO.File.WriteAllText
參考:如何:寫入文字檔 (C# 程式設計手冊)
備份:(2017/12/21)


如何:寫入文字檔 (C# 程式設計手冊)

在下列這些範例中,會示範幾個將文字寫入檔案的方法。 前兩個範例會在 System.IO.File 類別上使用靜態便利方法,將任何 IEnumerable<字串> 的每個項目和字串寫入文字檔。 範例 3 中會示範寫入檔案時,如何在需要分別處理每一行時,將文字加入至檔案。 範例 1-3 會覆寫檔案中所有現有的內容,但是範例 4 將示範如何將文字附加至現有的檔案。

這些範例全都會將字串常值寫入至檔案,不過您可能比較想要使用 Format 方法,該方法提供許多控制項讓您撰寫不同類型的值,在欄位中靠右或靠左對齊、使用或不使用邊框間距等等。 您也可以使用 C# 字串插值功能。

範例

C#
class WriteTextFile
{
    static void Main()
    {

        // These examples assume a "C:\Users\Public\TestFolder" folder on your machine.
        // You can modify the path if necessary.
        

        // Example #1: Write an array of strings to a file.
        // Create a string array that consists of three lines.
        string[] lines = { "First line", "Second line", "Third line" };
        // WriteAllLines creates a file, writes a collection of strings to the file,
        // and then closes the file.  You do NOT need to call Flush() or Close().
          // 建立檔案,不需要呼叫Flush()、Close().
        System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);


        // Example #2: Write one string to a text file.
        string text = "A class is the most powerful data type in C#. Like a structure, " +
                       "a class defines the data and behavior of the data type. ";
        // WriteAllText creates a file, writes the specified string to the file,
        // and then closes the file.    You do NOT need to call Flush() or Close().
          // 建立檔案,不需要呼叫Flush()、Close().
        System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);

        // Example #3: Write only some strings in an array to a file.
        // The using statement automatically flushes AND CLOSES the stream and calls 
        // IDisposable.Dispose on the stream object.
        // NOTE: do not use FileStream for text files because it writes bytes, but StreamWriter
        // encodes the output as text.
          // 使用using,自動Flush()、Close()、Dispose().
        using (System.IO.StreamWriter file = 
            new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
        {
            foreach (string line in lines)
            {
                // If the line doesn't contain the word 'Second', write the line to the file.
                if (!line.Contains("Second"))
                {
                    file.WriteLine(line);
                }
            }
        }

        // Example #4: Append new text to an existing file.
        // The using statement automatically flushes AND CLOSES the stream and calls 
        // IDisposable.Dispose on the stream object.
          // 使用using,自動Flush()、Close()、Dispose().
        using (System.IO.StreamWriter file = 
            new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
        {
            file.WriteLine("Fourth line");
        }
    }
}
 //Output (to WriteLines.txt):
 //   First line
 //   Second line
 //   Third line
     
 //Output (to WriteText.txt):
 //   A class is the most powerful data type in C#. Like a structure, a class defines the data and behavior of the data type.
     
 //Output to WriteLines2.txt after Example #3:
 //   First line
 //   Third line
      
 //Output to WriteLines2.txt after Example #4:
 //   First line
 //   Third line
 //   Fourth line

這些範例全都會將字串常值寫入至檔案,不過您可能比較想要使用 Format 方法,該方法提供許多控制項讓您撰寫不同類型的值,在欄位中靠右或靠左對齊、使用或不使用邊框間距等等。 您也可以使用 C# 字串插值功能。

穩固程式設計

以下條件可能會造成例外狀況:

  • 該檔案存在而且是唯讀的。
  • 路徑名稱可能太長。
  • 磁碟可能已滿。

另請參閱

C# 程式設計指南
檔案系統和登錄 (C# 程式設計指南)
範例:如何將集合儲存至應用程式儲存空間


 

參考:File.CreateText 方法 (String)
備份:(2017/12/21)


File.CreateText 方法 (String)

.NET Framework (current version)

建立或開啟用以寫入 UTF-8 編碼文字的檔案。

命名空間:   System.IO
組件:  mscorlib (於 mscorlib.dll)
 
語法
 
C#
public static StreamWriter CreateText(
	string path
)

參數
path
Type: System.String
要被開啟來寫入的檔案。

傳回值
Type: System.IO.StreamWriter
StreamWriter,使用 UTF-8 編碼方式寫入指定檔案。

Exception Condition
UnauthorizedAccessException

呼叫端沒有必要的權限。

ArgumentException

path 為零長度字串,只包含空格,或包含一或多個如 InvalidPathChars 所定義的無效字元。

ArgumentNullException

pathnull

PathTooLongException

指定的路徑、檔案名稱,或兩者都超出系統定義的長度上限。 例如,在 Windows 架構的平台上,路徑必須少於 248 個字元,檔案名稱必須少於 260 個字元。

DirectoryNotFoundException

指定的路徑無效 (例如,它位於未對應的磁碟機上)。

NotSupportedException

path 格式無效。

註解

This method is equivalent to the M:System.IO.StreamWriter.#ctor(System.String,System.Boolean) constructor overload with the append parameter set to false. If the file specified by path does not exist, it is created. If the file does exist, its contents are overwritten. Additional threads are permitted to read the file while it is open.

The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see M:System.IO.Directory.GetCurrentDirectory.

For a list of common I/O tasks, see Common I/O Tasks.

範例

The following example creates a file for text writing and reading.

C#
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        if (!File.Exists(path)) 
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path)) 
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }	
        }

        // Open the file to read from.
        using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }
    }
}
安全性
FileIOPermission
for writing to the specified file. Associated enumeration: F:System.Security.Permissions.FileIOPermissionAccess.Write
 
通用 Windows 平台
自 10 起供應
.NET Framework
自 1.1 起供應
Silverlight
自 2.0 起供應
Windows Phone Silverlight
自 7.0 起供應

 

 

參考:如何:將文字寫入檔案 (合集)
備份:(2017/12/21)


如何:將文字寫入檔案

.NET Framework (current version) 

本主題示範可針對 .NET Framework 應用程式或 Windows 8.x 市集 應用程式,將文字寫入至檔案的幾種不同方式。 通常會使用下列類別和方法,將文字寫入至檔案:

範例已經過簡化,以便專注於正在執行的工作。 因此,這些範例會執行最少的錯誤檢查和例外狀況處理 (如果有)。 真實世界應用程式通常會提供更強大的錯誤檢查和例外狀況處理。

範例

下列範例示範如何使用 StreamWriter 類別,以同步方式一次一行將文字寫入至新檔案。 新的文字檔會儲存到使用者的 [我的文件] 資料夾。 由於 StreamWriter 物件是在 using 陳述式中宣告及具現化,因此會叫用 Dispose 方法,自動清除並關閉資料流。

// Create a string array with the lines of text
string[] lines = { "First line", "Second line", "Third line" };

// Set a variable to the My Documents path.
string mydocpath =
    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

// Write the string array to a new file named "WriteLines.txt".
using (StreamWriter outputFile = new StreamWriter(mydocpath + @"\WriteLines.txt")) {
    foreach (string line in lines)
        outputFile.WriteLine(line);
}

範例

下列範例示範如何使用 StreamWriter 類別,將文字附加至現有的檔案。 它會使用來自上一個範例的相同文字檔。

// Set a variable to the My Documents path.
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

// Append text to an existing file named "WriteLines.txt".
using (StreamWriter outputFile = new StreamWriter(mydocpath + @"\WriteLines.txt", true)) {
    outputFile.WriteLine("Fourth Line");
}

範例

下列範例示範如何使用 StreamWriter 類別,以非同步方式將文字寫入至新檔案。 若要叫用 WriteAsync 方法,必須在 async 方法中呼叫此方法。 新的文字檔會儲存到使用者的 [我的文件] 資料夾。

static async void WriteTextAsync(string text)
{
    // Set a variable to the My Documents path.
    string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

    // Write the text asynchronously to a new file named "WriteTextAsync.txt".
    using (StreamWriter outputFile = new StreamWriter(mydocpath + @"\WriteTextAsync.txt")) {
        await outputFile.WriteAsync(text);
    }
}

範例

下列範例示範如何使用 File 類別,將文字寫入至新檔案,並將新的文字行附加至相同的檔案。 WriteAllTextAppendAllLines 方法會自動開啟和關閉檔案。 如果提供給 WriteAllText 方法的路徑已經存在,則會覆寫該檔案。

// Create a string array with the lines of text
string text = "First line" + Environment.NewLine;

// Set a variable to the My Documents path.
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

// Write the text to a new file named "WriteFile.txt".
File.WriteAllText(mydocpath + @"\WriteFile.txt", text);

// Create a string array with the additional lines of text
string[] lines = { "New line 1", "New line 2" };

// Append new lines of text to the file
File.AppendAllLines(mydocpath + @"\WriteFile.txt", lines);

範例

下面範例示範如何以非同步方式,將使用者輸入寫入至 Windows 8.x 市集 應用程式中的文字檔。 基於安全考量,從 Windows 8.x 市集 應用程式開啟檔案時,通常會需要使用 FileOpenPicker 控制項。 在這個範例中,FileOpenPicker 已篩選為顯示文字檔。

<Page
    x:Class="OpenFileWindowsStore.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:OpenFileWindowsStore"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Button Content="save text to a file" HorizontalAlignment="Left" Margin="103,417,0,0" VerticalAlignment="Top" 
                Width="329" Height="86" FontSize="35" Click="Button_Click"/>
        <TextBox Name="UserInputTextBox"  FontSize="18" HorizontalAlignment="Left" Margin="106,146,0,0" 
                 TextWrapping="Wrap" Text="Write some text here, and select a file to write it to." VerticalAlignment="Top" 
                 Height="201" Width="558" AcceptsReturn="True"/>
        <TextBlock Name="StatusTextBox" HorizontalAlignment="Left" Margin="106,570,0,147" TextWrapping="Wrap" Text="Status:" 
                   VerticalAlignment="Center" Height="51" Width="1074" FontSize="18" />
    </Grid>
</Page>
using System;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Storage;
using System.Text;
using Windows.Storage.Pickers;
using Windows.UI.Popups; 

namespace OpenFileWindowsStore
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        // Create a file picker to open a file. Most file access in Windows Store Apps
        // requires the use of a file picker for security purposes.
        FileOpenPicker picker = new FileOpenPicker();
        private async void Button_Click(object sender, RoutedEventArgs e)
        {

           // Set properties on the file picker such as start location and the type 
            // of files to display.
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.ViewMode = PickerViewMode.List;
            picker.FileTypeFilter.Add(".txt");

            // Show picker enabling user to pick one file.
            StorageFile result = await picker.PickSingleFileAsync();

            if (result != null)
            {
                try
                {
                    // Use FileIO to replace the content of the text file
                    await FileIO.WriteTextAsync(result, UserInputTextBox.Text);

                    // Display a success message
                    StatusTextBox.Text = "Status: File saved successfully";
                }
                catch (Exception ex)
                {
                    // Display an error message
                    StatusTextBox.Text = "Status: error saving the file - " + ex.Message;
                }
            }
            else
                StatusTextBox.Text = "Status: User cancelled save operation";
        }
    }
}

 

 

 

參考:C# FileStream和StreamWriter用法
備份:(2017/12/21)


201208091523[轉載]C# FileStream和StreamWriter用法

FileStream類操作的是字節和節節數組,而stream類操作的是字符數據。字符數據易於使用,但是有些操作,比如隨機文件訪問(訪問文件中間某點的數據),就必須由FileStream對象執行。
             FielStream類維護內部文件指針,該指針指向文件中進行下一次讀寫操作的位置。
             FileStream只能處理原始字節(raw byte),處理原去吧字節的功能使用FileStream類可以用於處理任何數據文件。
             通過讀取字節數據,FileStream對像可以用於讀取圖像和聲音。代價是FileStream類不能將數據直接讀入字符串
             此指針可以修改用Seek方法,它有兩個參數:
             第一個參數:規定文件指針以字節為參數的移動距離
             第二個參數:規定開始計算的起始位置

-----------------------------------------------------------------------------------------------------
        byte[] byDataValue = new byte[200];
        char[] charDataValue = new char[200];

        ///
        /// FilesStream讀取用法

        ///
        private void FilesStreamReadFile()
        {
            try
            {
                FileStream fsFile = new FileStream(@"d:\log.cs", FileMode.Open);
                //文件指針移到文件的135個字節
                fsFile.Seek(135, SeekOrigin.Begin);
                //將接下來的字節讀到Array中
                fsFile.Read(byDataValue, 0, 200);
            }
            catch (Exception e)
            {
                throw e;
            }
            //將字節轉換成字符
            Decoder dc = Encoding.UTF8.GetDecoder();
            //字節數組轉換成字符數組,便於顯示
            dc.GetChars(byDataValue, 0, byDataValue.Length, charDataValue, 0);

        }
----------------------------------------------------------------------------------------------
        ///
        /// FilesStream寫入用法
        ///
        private void FileStreamWriteFile()
        {
            FileStream fsFile = new FileStream(@"D:\log.txt", FileMode.Create);
            charDataValue="This is test string".ToCharArray();
            byDataValue=new byte[charDataValue.Length];

            //將字符數組轉換成字節數組
            Encoder ec=Encoding.UTF8.GetEncoder();
            ec.GetBytes(charDataValue,0,charDataValue.Length,byDataValue,0,true);

            //將指針設定起始位置
            fsFile.Seek(0,SeekOrigin.Begin);
            //寫入文件
            fsFile.Write(byDataValue,0,byDataValue.Length);
        }

-----------------------------------------------------------------------------------------------------
        ///
        /// StreamWriter寫入方法
        ///
        private void StreamWriterMetod()
        {
            try
            {
                FileStream fsFile = new FileStream(@"d:\log.txt",FileMode.OpenOrCreate);
                StreamWriter swWriter = new StreamWriter(fsFile);
                //寫入數據
                swWriter.WriteLine("Hello Wrold.");
                swWriter.WriteLine("It is now {0}", DateTime.Now.ToLongDateString());   
                swWriter.Close();
            }
            catch (Exception e)
            {
                throw e;
            }
        }

-------------------------------------------------------------------------------------------------------
        ///
        /// StreamWriter讀取方法
        ///
        private void StreamReaderMetod()
        {
            string sLine = "";
            try
            {
                FileStream fsFile = new FileStream(@"d:\log.txt", FileMode.Open);
                StreamReader srReader = new StreamReader(fsFile);
                //讀取文件(讀取大文件時,最好不要用此方法)
                sLine = srReader.ReadToEnd();
                txbValue.Text = sLine;
                srReader.Close();
            }
            catch (Exception e)
            {
                throw e;
            }
        }

----------------------------------------------------------------------------------
        ///
        /// StreamWriter讀取方法2
        ///
        private void StreamReaderMetodTwo()
        {
            try
            {
                FileStream fsFile = new FileStream(@"d:\log.txt", FileMode.Open);
                /*
                 * 讀取數據最簡單的方法是Read()。此方法將流的下一個字符作為正整數值返回,
                 * 如果達到了流的結尾處,則返回-1。
                 */
                StreamReader srReader = new StreamReader(fsFile);
                int iChar;
                iChar = srReader.Read();
                while (iChar != -1)
                {
                    txbValue.Text += (Convert.ToChar(iChar));
                    iChar = srReader.Read();
                }
                srReader.Close();
            }
            catch (Exception e)
            {
                throw e;
            }
        }

<h1>----------------------------------------------------------------------
</h1><h1>FileStream Open File [C#]</h1>

This example shows how to open files for reading or writing, how to load and save files using FileStream in C#. To open file create instance of FileStream class with FileMode and FileAccess enumerations as parameters.

<h2>FileStream typical use</h2>

This is typical code when opening file using FileStream. It's important to always close the stream. If you don't close the stream it can take a minute to be file again accessible (it will wait to garbage collector to free the FileStream instance and close the file).

[C#]
using System.IO;

FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Open);
try
{
 // read from file or write to file
}
finally
{
 fileStream.Close();
}
--------------------------------
<h2>Open file examples</h2>

Following examples show the most common cases how to open a file for reading or writing or how to create a file.

[C#] Open existing file for read and write.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Open);

[C#] Open existing file for reading.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read);

[C#] Open existing file for writing.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Write);

[C#] Open file for writing (with seek to end), if the file doesn't exist create it.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Append);

[C#] Create new file and open it for read and write, if the file exists overwrite it.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Create);

[C#] Create new file and open it for read and write, if the file exists throw exception.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.CreateNew);


reference:
http://www.csharp-examples.net/filestream-open-file/
http://www.cnblogs.com/scottckt/archive/2008/07/01/1233523.html
--------------------------------------------------------------------------------------------------


 

arrow
arrow

    Robert 發表在 痞客邦 留言(0) 人氣()