Table of Contents
Introduction
Only for existing files?
1. File.AppendAllText(String, String) method
algorithm
Example
Output
2. File.AppendText() method
示例
输出
StreanWriter 算法(字符串、布尔值)
时间复杂度
结论
Home Backend Development C#.Net Tutorial C# program to append text to existing file

C# program to append text to existing file

Sep 18, 2023 am 09:19 AM

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

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
How to use various symbols in C language How to use various symbols in C language Apr 03, 2025 pm 04:48 PM

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

What is the role of char in C strings What is the role of char in C strings Apr 03, 2025 pm 03:15 PM

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

How to handle special characters in C language How to handle special characters in C language Apr 03, 2025 pm 03:18 PM

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

How to convert char in C language How to convert char in C language Apr 03, 2025 pm 03:21 PM

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

The difference between char and wchar_t in C language The difference between char and wchar_t in C language Apr 03, 2025 pm 03:09 PM

In C language, the main difference between char and wchar_t is character encoding: char uses ASCII or extends ASCII, wchar_t uses Unicode; char takes up 1-2 bytes, wchar_t takes up 2-4 bytes; char is suitable for English text, wchar_t is suitable for multilingual text; char is widely supported, wchar_t depends on whether the compiler and operating system support Unicode; char is limited in character range, wchar_t has a larger character range, and special functions are used for arithmetic operations.

Common errors and ways to avoid char in C language Common errors and ways to avoid char in C language Apr 03, 2025 pm 03:06 PM

Errors and avoidance methods for using char in C language: Uninitialized char variables: Initialize using constants or string literals. Out of character range: Compare whether the variable value is within the valid range (-128 to 127). Character comparison is case-insensitive: Use toupper() or tolower() to convert character case. '\0' is not added when referencing a character array with char*: use strlen() or manually add '\0' to mark the end of the array. Ignore the array size when using char arrays: explicitly specify the array size or use sizeof() to determine the length. No null pointer is not checked when using char pointer: Check whether the pointer is NULL before use. Use char pointer to point to non-character data

What is the difference between char and unsigned char What is the difference between char and unsigned char Apr 03, 2025 pm 03:36 PM

char and unsigned char are two data types that store character data. The main difference is the way to deal with negative and positive numbers: value range: char signed (-128 to 127), and unsigned char unsigned (0 to 255). Negative number processing: char can store negative numbers, unsigned char cannot. Bit mode: char The highest bit represents the symbol, unsigned char Unsigned bit. Arithmetic operations: char and unsigned char are signed and unsigned types, and their arithmetic operations are different. Compatibility: char and unsigned char

See all articles