當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# File.CreateText()用法及代碼示例

File.CreateText()是內置的File類方法,用於用給定的UTF-8編碼文本覆蓋現有文件的內容,如果尚未創建文件,則此函數將創建具有指定內容的新文件。

用法:

public static System.IO.StreamWriter CreateText (string path);

參數:該函數接受如下所示的參數:



  • Path: This is the file where UTF-8 encoded texts are going to be overwritten. The file is created if it doesn’t already exist.

異常:

  • UnauthorizedAccessException:調用者沒有所需的權限。或路徑指定了隻讀文件。或路徑指定了隱藏的文件。
  • ArgumentException:路徑是長度為零的字符串,僅包含空格或一個或多個無效字符。
  • ArgumentNullException:路徑為空。
  • PathTooLongException:指定的路徑,文件名或兩者都超過了system-defined的最大長度。
  • DirectoryNotFoundException:指定的路徑無效,即它位於未映射的驅動器上。
  • NotSupportedException:路徑格式無效。

返回值:返回使用UTF-8編碼寫入指定文件的StreamWriter。

下麵是說明File.CreateText()方法的程序。

程序1:

在運行以下代碼之前,將創建一個文件file.txt,其中包含一些內容,如下所示:

file.txt

// C# program to illustrate the usage 
// of File.CreateText() method 
  
// Using System, System.IO namespaces 
using System; 
using System.IO; 
  
class GFG { 
    // Main method 
    public static void Main() 
    { 
        // Creating a file 
        string myfile = @"file.txt"; 
  
        // Overwriting to the above existing file 
        using(StreamWriter sw = File.CreateText(myfile)) 
        { 
            sw.WriteLine("GeeksforGeeks"); 
            sw.WriteLine("is a"); 
            sw.WriteLine("computer science"); 
            sw.WriteLine("portal."); 
        } 
  
        // Opening the file for reading 
        using(StreamReader sr = File.OpenText(myfile)) 
        { 
            string s = ""; 
            while ((s = sr.ReadLine()) != null) { 
                Console.WriteLine(s); 
            } 
        } 
    } 
}

執行中:

mcs -out:main.exe main.cs
mono main.exe
GeeksforGeeks
is a
computer science
portal.

運行以上代碼後,將顯示以上輸出,並且現有文件file.txt如下所示:

file.txt

程序2:最初,沒有創建文件,因此下麵的代碼本身創建了一個名為file.txt的文件

// C# program to illustrate the usage 
// of File.CreateText() method 
  
// Using System, System.IO namespaces 
using System; 
using System.IO; 
  
class GFG { 
    // Main method 
    public static void Main() 
    { 
        // Creating a file 
        string myfile = @"file.txt"; 
  
        // Checking the existance of above file 
        if (!File.Exists(myfile)) { 
            // Creating a new file with below contents 
            using(StreamWriter sw = File.CreateText(myfile)) 
            { 
                sw.WriteLine("Geeks"); 
                sw.WriteLine("GFG"); 
                sw.WriteLine("GeeksforGeeks"); 
            } 
        } 
  
        // Opening the file for reading 
        using(StreamReader sr = File.OpenText(myfile)) 
        { 
            string s = ""; 
            while ((s = sr.ReadLine()) != null) { 
                Console.WriteLine(s); 
            } 
        } 
    } 
}

執行中:

mcs -out:main.exe main.cs
mono main.exe
Geeks
GFG
GeeksforGeeks

運行上述代碼後,將創建一個新文件file.txt,如下所示:

file.txt




相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 File.CreateText() Method in C# with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。