Home  >  Article  >  Backend Development  >  C# program creates and writes files

C# program creates and writes files

PHPz
PHPzforward
2023-09-01 15:21:031055browse

C# 程序创建文件并写入文件

introduce

Creating files and writing content into them are the basics of file processing. Here, we will discuss a method for writing a C# program to create and write files. In layman's terms, file processing or file management refers to various processes such as creating files, reading from files, writing to files, appending files, and so on. Viewing and writing files are two of the most common operations in file management.

Input and output occur because streams provide a universal view of byte sequences. Stream is an abstract class. It is a gateway for different processes i.e. input and output. Using file streams in C# file processing. Now. Let us discuss the different methods of creating and writing files.

1. File.WriteAllText() method

This is one of the most commonly used methods and one of the easiest to use. This method creates a file by a programmer-defined name and writes the string input data into it. Once data entry is complete, the file will be closed. If the file the user wants to create already exists, the previous file in storage will be overwritten.

public static void WriteAllText (string path, string? contents); 

The input parameters are all strings. By default, UTF-8 encoding is used without BOM (Byte Order Mark). If the user wants to use a different encoding, they can pass a third parameter to specify a specific encoding.

algorithm

Now, let us discuss the algorithm for creating and writing files using the File.WriteAllText() method.

Step 1 - Declare the variable using a text file name.

Step 2 The string is declared as data.

Step 3 The information is entered into the file and stored in it.

Step 4 After the information is written, print the success message.

Example

using System.Text;
using System;
using System.IO;
class testfiles {
   public static void Main(){
      var loc = "tutpoint.txt";
      string inform = "Tutorials Point";
      File.WriteAllText(loc, inform);
      
      //The text input is done
      Console.WriteLine("Text input completed.");
   }
} 

Output

Text input completed. 

2. File.WriteAllLines() method

This method creates a file with a programmer-defined name and writes a single string input or multiple strings at once. After data entry is complete, the file is closed. If the file the user wants to create exists, the previous file in storage will be overwritten.

public static void WriteAllLines (string path, string[] contents); 

It uses UTF-8 encoding without BOM, i.e. Byte Order Mark.

algorithm

This algorithm is about File.WriteAllLines().

Step 1 - Declare the variable using a text file name.

Step 2 The string is declared as data.

Step 3 The data is written to the tutpoint.txt file.

Step 4 Write a line of code to display the successfully completed work.

Example

using System.Text;
using System;
using System.IO;
class testfiles {
   public static void Main(){
      var loc = "tutpoint.txt";
      string[] inform = {"Tutorials", "Point", "learn"};
      File.WriteAllLines(loc, inform);
      
      //The text input is done
      Console.WriteLine("Text input completed.");
   }
}

Output

Text input completed. 

3. File.WriteAllBytes() method

What if you want to create an entry of a byte array? Then we can use the File.WriteAllBytes() method. This method creates a file with a programmer-defined name. The byte array data is written to the file, and the file is closed. If the file the user wants to create already exists, the previous file in storage will be overwritten.

public static void WriteAllBytes (string path, byte[] bytes); 

algorithm

Now, let us discuss the algorithm for creating and writing files using the File.WriteAllBytes() method.

Step 1 - Declare the variable using a text file name.

Step 2 The string is declared as data.

Step 3 Enter the information into the file and store it in it.

Step 4 After the information is written, a success message will be printed.

Example

using System.Text;
using System;
using System.IO;
class testfiles {
   public static void Main(){
      var loc = "tutpoint.txt";
      string inform = "Tutorial point contains a plethora of technical articles";
      byte[] details = Encoding.ASCII.GetBytes(inform);
      File.WriteAllBytes(loc, details);
      
      //The text input is done
      Console.WriteLine("Text input completed.");
   }
} 

Output

Text input completed. 

4. Asynchronous method

If the user wishes to input data asynchronously rather than synchronously, C# also provides this function to the user. All the methods we discussed above can also be used in an asynchronous manner. Here we will discuss one of the methods and the rest can be implemented similarly.

We will learn about WriteAllTextAsync().

public static System.Threading.Tasks.Task WriteAllTextAsync (string path, string? contents, System.Threading.CancellationToken cancellationToken = default);

此方法以异步方式创建文件,然后将所有文本写入文件。之后,文件被关闭。

算法

现在,让我们讨论使用File.WriteAllTextAsync()方法创建文件和写入文件的算法。

步骤 1 − 变量使用文本文件名进行声明。

步骤2  字符串被声明为数据。

第 3 步 信息被输入到文件中并存储在其中。

第4步  在信息被写入后,打印成功消息。

示例

using System.Text;
using System;
using System.IO;
using System.Threading.Tasks;
class testfiles {
   public static void Main() {
      var loc = "tutpoint.txt";
      string inform = "falcon";
       
      // await File.WriteAllTextAsync(loc, inform);
      Task asyncTask = WriteFileAsync(loc, inform);
        
      //The text input is done
      Console.WriteLine("Text input completed.");
   }
   static async Task WriteFileAsync(string loc, string inform){
      Console.WriteLine("Async Write File has started.");
      using(StreamWriter outputFile = new StreamWriter(Path.Combine(loc)) ){
         await outputFile.WriteAsync(inform);
      }
      Console.WriteLine("Stage 2");
   }
} 

输出

Async Write File has started.
stage 2
Text input completed.

结论

所以,这篇文章就到这里结束了。在这篇文章中,我们学习了一个用C#编写文件和写入文件的程序。我们学习了各种方法来实现这一点。我们还讨论了不同的算法,并学习了它们的代码。我们希望这篇文章能够增加你对C#的了解。

The above is the detailed content of C# program creates and writes files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete