search
HomeBackend DevelopmentC#.Net TutorialC# program to append text to existing file

将文本附加到现有文件的 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); 

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);
   }
}

Output

UCL

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);
   }
} 

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); 

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);
   }
}

输出

UCL

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);
   } 
}

输出

UCL

时间复杂度

由于在这两个进程中,我们都使用文件处理。在第一个算法中,我们使用 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!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

C# .NET: Building Applications with the .NET EcosystemC# .NET: Building Applications with the .NET EcosystemApr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft