[C#] 파일을 읽고 쓰는 가장 쉬운 방법

C #에서 파일 ( 바이너리가 아닌 텍스트 파일) 을 읽고 쓰는 방법에는 여러 가지가 있습니다.

프로젝트에서 파일로 많은 작업을 할 것이기 때문에 쉽고 간단한 코드가 필요한 것이 필요합니다. 내가 필요한 것은 s string를 읽고 쓰는 것이므로 무언가가 필요합니다 string.



답변

File.ReadAllTextFile.WriteAllText를 사용하십시오 .

더 간단 할 수 없습니다 …

MSDN 예 :

// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);

// Open the file to read from.
string readText = File.ReadAllText(path);


답변

또한에 File.ReadAllText, File.ReadAllLines그리고 File.WriteAllText(에서와 유사한 도우미 File에 표시된 클래스) 다른 답변을 사용할 수 StreamWriter/ StreamReader클래스를.

텍스트 파일 작성 :

using(StreamWriter writetext = new StreamWriter("write.txt"))
{
    writetext.WriteLine("writing in text file");
}

텍스트 파일을 읽는 중 :

using(StreamReader readtext = new StreamReader("readme.txt"))
{
   string readText = readtext.ReadLine();
}

노트:

  • readtext.Dispose()대신 사용할 수 using있지만 예외가 발생하면 파일 / 리더 / 라이터가 닫히지 않습니다.
  • 상대 경로는 현재 작업 디렉토리에 상대적입니다. 절대 경로를 사용 / 구성 할 수 있습니다.
  • 누락 using/ Close“데이터가 파일에 기록되지 않는 이유”매우 일반적인 이유입니다.

답변

FileStream fs = new FileStream(txtSourcePath.Text,FileMode.Open, FileAccess.Read);
using(StreamReader sr = new StreamReader(fs))
{
   using (StreamWriter sw = new StreamWriter(Destination))
   {
            sw.writeline("Your text");
    }
}


답변

using (var file = File.Create("pricequote.txt"))
{
    ...........
}

using (var file = File.OpenRead("pricequote.txt"))
{
    ..........
}

작업이 완료되면 간단하고 쉬우 며 처리 / 정리도합니다.


답변

파일에서 읽고 파일에 쓰는 가장 쉬운 방법 :

//Read from a file
string something = File.ReadAllText("C:\\Rfile.txt");

//Write to a file
using (StreamWriter writer = new StreamWriter("Wfile.txt"))
{
    writer.WriteLine(something);
}


답변

@AlexeiLevenkov는 또 다른 “가장 쉬운 방법”, 즉 확장 방법을 지적했습니다 . 약간의 코딩이 필요하며 읽고 쓰는 가장 쉬운 방법을 제공하며 개인의 요구에 따라 변형을 만들 수있는 유연성을 제공합니다. 다음은 완전한 예입니다.

string유형 에 대한 확장 방법을 정의합니다 . 실제로 중요한 것은 extra keyword가있는 함수 인수 this이므로 메소드가 연결된 오브젝트를 참조하게합니다. 클래스 이름은 중요하지 않습니다. 클래스와 메소드 선언 해야 합니다 static.

using System.IO;//File, Directory, Path

namespace Lib
{
    /// <summary>
    /// Handy string methods
    /// </summary>
    public static class Strings
    {
        /// <summary>
        /// Extension method to write the string Str to a file
        /// </summary>
        /// <param name="Str"></param>
        /// <param name="Filename"></param>
        public static void WriteToFile(this string Str, string Filename)
        {
            File.WriteAllText(Filename, Str);
            return;
        }

        // of course you could add other useful string methods...
    }//end class
}//end ns

string extension method이것은를 사용하는 방법입니다. 자동으로 다음을 나타냅니다 class Strings.

using Lib;//(extension) method(s) for string
namespace ConsoleApp_Sandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            "Hello World!".WriteToFile(@"c:\temp\helloworld.txt");
            return;
        }

    }//end class
}//end ns

나는 이것을 직접 발견하지 못했지만 훌륭하게 작동하므로 이것을 공유하고 싶었습니다. 즐기세요!


답변

파일에 쓰거나 파일을 읽는 데 가장 일반적으로 사용되는 방법은 다음과 같습니다.

using System.IO;

File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it. 
File.ReadAllText(sFilePathAndName);

내가 대학에서 가르친 오래된 방법은 스트림 리더 / 스트림 라이터를 사용하는 것이었지만 File I / O 메서드는 덜 복잡하고 더 적은 코드 줄이 필요합니다. “파일”을 입력 할 수 있습니다. IDE에서 (System.IO import 문을 포함시켜야 함) 사용 가능한 모든 메소드를 확인하십시오. 다음은 Windows Forms 앱을 사용하여 텍스트 파일 (.txt)에서 문자열을 읽거나 쓰는 방법의 예입니다.

기존 파일에 텍스트를 추가하십시오.

private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
    string sTextToAppend = txtMainUserInput.Text;
    //first, check to make sure that the user entered something in the text box.
    if (sTextToAppend == "" || sTextToAppend == null)
    {MessageBox.Show("You did not enter any text. Please try again");}
    else
    {
        string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string.
        if (sFilePathAndName == "" || sFilePathAndName == null)
        {
            //MessageBox.Show("You cancalled"); //DO NOTHING
        }
        else
        {
            sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text
            File.AppendAllText(sFilePathAndName, sTextToAppend);
            string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1);
            MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
        }//end nested if/else
    }//end if/else

}//end method AppendTextToExistingFile_Click

파일 탐색기 / 파일 열기 대화 상자를 통해 사용자로부터 파일 이름을 가져옵니다 (기존 파일을 선택하려면이 파일이 필요함).

private string getFileNameFromUser()//returns file path\name
{
    string sFileNameAndPath = "";
    OpenFileDialog fd = new OpenFileDialog();
    fd.Title = "Select file";
    fd.Filter = "TXT files|*.txt";
    fd.InitialDirectory = Environment.CurrentDirectory;
    if (fd.ShowDialog() == DialogResult.OK)
    {
        sFileNameAndPath = (fd.FileName.ToString());
    }
    return sFileNameAndPath;
}//end method getFileNameFromUser

기존 파일에서 텍스트를 가져옵니다.

private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
    string sFileNameAndPath = getFileNameFromUser();
    txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}