C# program to append text to existing file

WBOY
Release: 2023-09-18 09:19:32
forward
1199 people have browsed it

将文本附加到现有文件的 C# 程序

Introduction

Append refers to adding information to an already written document. Here we will learn to write a C# program to append text to an existing file. As we all know, file handling is done in C#. Most of the time, files are used to store data. In layman's terms, file processing or file management are various processes such as creating files, reading files, writing files, appending files, and so on.

Only for existing files?

As we all know, append usually means adding a piece of information to an already written document. But what if the file we are trying to access does not exist? Let's say we are searching for a file called "madrid.txt" to attach it. If the file exists in the specified directory, the file is appended. But what if the file "madrid.txt" does not exist? The program will then create a new file called "madrid.txt" where you can add your information. So when we try to open a file in append mode, if that particular file does not exist, a new empty file is created with the same name as the file we want to append.

1. File.AppendAllText(String, String) method

The File.AppendAllText() method is a very common solution to the problem of appending to an existing file. This method comes from File class. The syntax of this method is as follows.

public static void AppendAllText (string path, string? contents); 
Copy after login

In the syntax, the first string contains the path to the file we want to append. After that, the information we want to add to the file is as follows. This may also throw some exceptions. If the directory where we are trying to access the file does not exist, DirectoryNotFoundException will be thrown. Another major exception thrown is UnauthorizedAccessException. This happens when the programmer tries to access a file that is read-only or the specified path points to a directory instead of a file.

When using this method, the file handle will be closed regardless of the exception thrown.

algorithm

Now, we will discuss the algorithm for creating a program to add information to a file using File.AppendAllText().

Step 1 - First, we create a string to store the address of the file to be attached and then provide the address of the file.

Step 2 - Then we use FileAppendAllText() to open the file in append mode and add the specific text to the file. If the file does not exist, a new file is created with the name and the text is added.

Step 3 - Finally, the text is read from the file so we can see the file is attached, and then the program exits.

Example

// A program to append the file
using System;
using System.IO;

public class Program {
   public static void Main() {
      string loca = @"D:\madrid.txt";

      // Adding the text to the madrid.txt file
      File.AppendAllText(loca, Environment.NewLine + "UCL");

      // Reading the text from the madrid.txt file
      string txtappd = File.ReadAllText(loca);
      Console.WriteLine(txtappd);
   }
}
Copy after login

Output

UCL
Copy after login
Copy after login
Copy after login

So, the path to the file is provided, and then the method opens the specified file, adds the information the programmer wants, and then closes the file. Simple enough, but what if we want to copy the entire contents of a file to the file we want? Yes, this method also solves our problem of copying files. Now it's time to discuss algorithms.

algorithm

This algorithm is about using File.AppendAllText().

Step 1 - Create a string to store the source file address.

Step 2 - Create another string to store the address of the target file.

Step 3 - File.Readlines() is used to copy the source file in a string.

Step 4 - The file is opened in append mode by File.AppendAllText(). Then add text.

Step 5 - Exit when the program is complete.

Example

// A program to append the file
using System;
using System.Collections.Generic;
using System.IO;

public class Program {
   public static void Main() {
      string sttr1 = @"D:\trophies.txt";
      string sttr2 = @"D:\madrid.txt";

      // Copying all the text from the source file in a string and then adding to the destination file
      IEnumerable<string> inform = File.ReadLines(sttr1);
      File.AppendAllLines(sttr2, inform);
   }
} 
Copy after login

Now let's look at another method.

2. File.AppendText() method

The SteamWriter class is a very general class. It provides many methods for writing files. WriteLine() or Write() are different methods that can be used to add text to a stream.

public static System.IO.StreamWriter AppendText (string path); 
Copy after login

You can create a StreamWriter instance using the File.AppendAllText() method, which appends text to an existing file in UTF-8 encoding. It also creates a new file if the specified file does not exist.

If the directory we are trying to access the file in does not exist, DirectoryNotFoundException will be thrown. Another major exception thrown is UnauthorizedAccessException. This happens when the programmer tries to access a file that is read-only or the specified path points to a directory instead of a file.

algorithm

Now, we will discuss the algorithm for creating a program to add information to a file using File.AppendText().

Step 1 - First, we create a string to store the address of the file to be attached and then provide the address of the file.

Step 2 - Now, we create an instance of StreamReader. This step opens the file in append mode and adds text to the file. We use File.AppendText() to add text.

StreamReader.Write() method is used for appending. If user wants to append text then add line terminator at the end. Use the StreamReader.WriteLine() method.

Step 3 - Exit when the program is complete.

示例

// A program to append the file
using System;
using System.IO;

public class Program {
   public static void Main() {
      string loca = @"D:\madrid.txt";

      // Adding the text to the specified file
      using (StreamWriter sw = File.AppendText(loca)) {
         sw.Write("UCL"); //use sw.WriteLine(If you want to add line termination)
      }

      // Read the text from the appended file
      string txtappd = File.ReadAllText(loca);
      Console.WriteLine(txtappd);
   }
}
Copy after login

输出

UCL
Copy after login
Copy after login
Copy after login

StreamWriter(String, Boolean) 构造函数重载版本也相当于 File.AppendText()。而对于布尔参数,我们使用 true。

StreanWriter 算法(字符串、布尔值)

现在,我们将讨论创建一个程序以使用 StreamWriter(String, Boolean) 将信息添加到文件的算法。

第 1 步 - 首先,我们创建一个字符串来存储要附加的文件的地址,然后提供文件的地址

第 2 步 现在,我们创建 StreamReader 的实例。此步骤以追加模式打开文件并向文件添加文本。我们使用新的 Streamwriter() 来添加信息。在这里,我们使用 StreamReader.Write() 方法进行追加。但如果我们需要附加文本,然后在末尾添加行终止符,那么我们可以使用 StreamReader.WriteLine() 方法。

第 3 步 最后,从文件中读取文本,以便我们可以看到文件已附加,然后程序退出。

示例

// A program to append the file
using System;
using System.IO;

public class Program {
   public static void Main() {
      string loca = @"D:\madrid.txt";

      // Adding the text to the specified file
      using (StreamWriter sw = new StreamWriter(loca, true)) {
         sw.Write("UCL"); //use sw.WriteLine(If you want to add line termination)
      }

      // Read the text from the appended file
      string txtappd = File.ReadAllText(loca);
      Console.WriteLine(txtappd);
   } 
}
Copy after login

输出

UCL
Copy after login
Copy after login
Copy after login

时间复杂度

由于在这两个进程中,我们都使用文件处理。在第一个算法中,我们使用 File.AppendAllText(),在第二个算法中,我们使用 File.AppendText(),它们都只是附加文件。他们正在获取新文本并将其添加到文件末尾。所以,这两种方法的时间复杂度都是O(1)。

结论

在本文中,我们讨论了将文本附加到现有文件的不同方法。首先我们讨论了是否需要以及是否只能对现有文件进行。然后我们讨论了追加File.AppendAllText()和File.AppendText()的方法。最后,我们讨论了算法和算法的代码。

我们希望本文能够帮助您增强有关 C# 的知识。

The above is the detailed content of C# program to append text to existing file. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!