>  기사  >  백엔드 개발  >  C# 스트림라이터

C# 스트림라이터

WBOY
WBOY원래의
2024-09-03 15:23:32571검색

특정 인코딩을 따르는 스트림에 문자를 쓰려면 C#에서 StreamWriter 클래스라는 클래스를 사용하고 StreamWriter 클래스의 StreamWriter.Write() 메서드는 스트림에 문자를 쓰는 작업을 담당합니다. TextWriter 클래스는 StreamWriter 클래스인 StreamWriter 클래스의 기본 클래스이며 TextWriter 클래스에서 상속되며 이 TextWriter 클래스는 개체를 문자열에 쓰기, 파일에 문자열 쓰기, XML 직렬화 등에 사용할 수 있는 여러 메서드를 제공합니다. System.IO.namespace는 StreamWriter가 정의된 네임스페이스이며 StreamWriter 클래스는 Write, WriteAsync, WriteLine, WriteLineAsync 등과 같은 여러 Write 메서드를 제공합니다.

C#의 StreamWriter 클래스 구문은 다음과 같습니다.

public class StreamWriter : System.IO.TextWriter

C#에서 StreamWriter 클래스 작업

  • 스트림은 C#의 파일 작업에서 파일에서 데이터를 읽고 파일에 데이터를 쓰는 데 사용됩니다.
  • 애플리케이션과 파일 사이에 생성되는 추가 레이어를 스트림이라고 합니다.
  • 스트림을 사용하면 파일을 원활하게 읽고 파일에 데이터를 원활하게 쓸 수 있습니다.
  • 대용량 파일의 데이터는 작은 덩어리로 분할된 후 스트림으로 전송됩니다. 그런 다음 애플리케이션은 전체 데이터를 한 번에 읽으려고 시도하는 대신 스트림에서 이러한 데이터 덩어리를 읽습니다. 이것이 스트림 이용의 장점입니다.
  • 파일의 데이터를 작은 덩어리로 나누는 이유는 애플리케이션이 파일의 전체 데이터를 한 번에 읽으려고 할 때 애플리케이션 성능에 영향을 미치기 때문입니다.
  • 따라서 데이터를 파일에 쓸 때마다 데이터가 먼저 스트림에 쓰여진 다음 스트림에서 파일에 데이터가 쓰여집니다.

C# StreamWriter의 예

StreamWriter를 사용하여 파일에 데이터를 쓰는 방법을 보여주기 위해 아래 예를 고려하세요.

예시 #1

코드:

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//a namespace called program is defined
namespace program
{
//a class called check is defined
class check
{
//main method is called
static void Main(string[] args)
{
//the path of the file and the file name is assigned to a string variable
String pat = @"D:\Ex.txt";
//an instance of the string writer class is created, and the path of the file is passed as a parameter to append text to the file
using (StreamWriter sw = File.AppendText(pat))
{
//data to be appended to the file is included
sw.WriteLine("Welcome to StreamWriter class in C#");
//the instance of the streamwriter class is closed after writing data to the File
sw.Close();
//data is read from the file by taking the path of the file as parameter
Console.WriteLine(File.ReadAllText(pat));
}
Console.ReadKey();
}
}
}

출력:

C# 스트림라이터

위 프로그램에는 program이라는 네임스페이스가 정의되어 있습니다. 그런 다음 check라는 클래스가 정의됩니다. 그런 다음 기본 메서드가 호출됩니다. 그런 다음 파일 경로와 파일 이름이 문자열 변수에 할당됩니다. 그런 다음 문자열 작성기 클래스의 인스턴스가 생성되고 파일 경로가 매개 변수로 전달되어 파일에 텍스트를 추가합니다. 그런 다음 파일에 추가할 데이터가 포함됩니다. 그런 다음 파일에 데이터를 쓴 후 스트림 작성기 클래스의 인스턴스가 닫힙니다. 그런 다음 파일 경로를 매개변수로 사용하여 파일에서 데이터를 읽습니다.

예시 #2

StreamWriter 클래스 사용법을 보여주는 프로그램:

코드:

using System.IO;
//a class called check is defined
class check
{
//main method is called
static void Main()
{
//an instance of streamwriter class is created and the path of the file is passed as a parameter
using (StreamWriter sw = new StreamWriter(@"D:\imp.txt"))
{
//write() method of stream writer class is used to write the first line so that the next line continues from here
sw.Write("Welcome to StreamWriter class in C# and ");
//writeline() method is used to write the second line and the next line starts from a new line
sw.WriteLine("this program is demonstration of StreamWriter class in C# ");
//writeline() method is used to write the third line and the next line starts from a new line
sw.WriteLine("I hope you are learning ");
}
}
}

출력:

C# 스트림라이터

위 프로그램에는 check라는 클래스가 정의되어 있습니다. 그런 다음 기본 메서드가 호출됩니다. 그런 다음 스트림 기록기 클래스의 인스턴스가 생성되고 파일 경로가 스트림 기록기가 데이터를 쓰는 매개 변수로 전달됩니다. 그런 다음 스트림 라이터 클래스의 write() 메서드를 사용하여 여기에서 다음 줄이 계속되도록 첫 번째 줄을 작성합니다. 그런 다음 writeline() 메서드를 사용하여 두 번째 줄을 쓰고 다음 줄은 새 줄에서 시작됩니다. 그런 다음 writeline() 메서드를 사용하여 세 번째 줄을 쓰고 다음 줄은 새 줄에서 시작됩니다. 프로그램의 출력은 위의 스냅샷과 같습니다.

예시 #3

StreamWriter 클래스 사용법을 보여주는 프로그램:

코드:

using System.IO;
//a class called check is defined
class check
{
//main method is called
static void Main()
{
//an instance of the stream writer class is created and the path of the file to which the data must be written is passed as a parameter
using (StreamWriter sw = new StreamWriter(@"D:\Ex.txt"))
{
//a variable called plane is defined
string plane = "Tejas";
//an integer called high is defined
int high = 120;
//interpolation syntax in string is used to make code efficient.
sw.WriteLine($"The plane {plane} flies {high} feet high.");
}
}
}

출력:

C# 스트림라이터

위 프로그램에는 check라는 클래스가 정의되어 있습니다. 그런 다음 기본 메서드가 호출됩니다. 그런 다음 스트림 기록기 클래스의 인스턴스가 생성되고 데이터를 써야 하는 파일의 경로가 매개 변수로 전달됩니다. 그런 다음 plane이라는 변수가 정의됩니다. 그런 다음 high라는 정수가 정의됩니다. 그런 다음 문자열의 보간 구문을 사용하여 코드를 효율적으로 만듭니다. 프로그램의 출력은 위의 스냅샷과 같습니다.

결론

이 튜토리얼에서는 C#의 StreamWriter 클래스 정의, C#의 StreamWriter 클래스 구문, 프로그래밍 예제 및 출력을 통해 StreamWriter 클래스의 작동 방식을 통해 C#의 StreamWriter 클래스 개념을 이해합니다.

위 내용은 C# 스트림라이터의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:C# 스트림리더다음 기사:C# 스트림리더