sourcetip

파일 읽기 및 쓰기 가장 쉬운 방법

fileupload 2023. 4. 18. 23:14
반응형

파일 읽기 및 쓰기 가장 쉬운 방법

C#에서는 파일(이진수가 아닌 텍스트 파일)을 읽고 쓰는 방법이 많이 있습니다.

프로젝트에서는 파일을 많이 다룰 예정이기 때문에 간단하고 최소한의 코드만을 사용하는 것이 필요합니다.필요한 것은 이것뿐입니다.string읽고 쓰기만 하면 되니까strings.

파일을 사용합니다.Read AllText and File.Write AllText.

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(또, 같은 조력자의Fileclass)는 / classes를 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();
}

주의:

  • 대신 을 사용할 수 있지만 예외의 경우 파일/읽기/라이터를 닫지 않습니다.
  • 상대 경로는 현재 작업 디렉토리에 상대 경로입니다.절대 경로를 사용하거나 구성할 수 있습니다.
  • 실종된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");
    }
}

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

//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);
}
using (var file = File.Create("pricequote.txt"))
{
    ...........                        
}

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

단순하고 간단하며 오브젝트 처리가 완료되면 오브젝트를 폐기/청소할 수 있습니다.

@Alexei Levenkov는 나에게 또 다른 "가장 쉬운 방법"을 알려주었다. 바로 연장법이다.약간의 코딩만 하면 읽기/쓰기가 가장 쉬워집니다.게다가, 개인의 요구에 맞추어 유연하게 변형을 작성할 수 있습니다.다음으로 완전한 예를 제시하겠습니다.

이것에 의해, 에서의 확장 방식이 정의됩니다.stringtype. 정말 중요한 것은 추가 키워드를 포함한 함수 인수뿐입니다.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);

대학에서 배운 예전 방식은 스트림 리더/스트림 라이터를 사용하는 것이었지만 파일 I/O 방식은 덜 투박하고 코드 행이 적게 필요합니다.IDE 에 「파일」을 입력할 수 있습니다(시스템이 포함되어 있는 것을 확인해 주세요).IO Import 스테이트먼트) 및 사용 가능한 모든 메서드를 확인합니다.다음은 Windows Forms App을 사용하여 텍스트 파일(.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
}

또는 정말로 선에 관한 것이라면:

System.IO.파일에는 정적 메서드 WriteAllLines도 포함되어 있으므로 다음을 수행할 수 있습니다.

IList<string> myLines = new List<string>()
{
    "line1",
    "line2",
    "line3",
};

File.WriteAllLines("./foo", myLines);

읽을 때는 OpenFileDialog 컨트롤을 사용하여 읽고 싶은 파일을 찾아보는 것이 좋습니다.아래에서 코드를 찾습니다.

다음 도 꼭 넣어주세요using: " " statement statement statement statement : "using System.IO;

private void button1_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
         textBox1.Text = File.ReadAllText(openFileDialog1.FileName);  
    }
}

쓸는 '파일을 쓸 수 있다'는 쓸 수 있습니다.File.WriteAllText.

     class Program
    { 
         public static void Main()
        { 
            //To write in a txt file
             File.WriteAllText("C:\\Users\\HP\\Desktop\\c#file.txt", "Hello and Welcome");

           //To Read from a txt file & print on console
             string  copyTxt = File.ReadAllText("C:\\Users\\HP\\Desktop\\c#file.txt");
             Console.Out.WriteLine("{0}",copyTxt);
        }      
    }
private void Form1_Load(object sender, EventArgs e)
    {
        //Write a file
        string text = "The text inside the file.";
        System.IO.File.WriteAllText("file_name.txt", text);

        //Read a file
        string read = System.IO.File.ReadAllText("file_name.txt");
        MessageBox.Show(read); //Display text in the file
    }
  1. 파일에서 읽기
string filePath = @"YOUR PATH";
List<string> lines = File.ReadAllLines(filePath).ToList();
  1. 파일에 쓰는 중
List<string> lines = new List<string>();
string a = "Something to be written"
lines.Add(a);
File.WriteAllLines(filePath, lines);

심플:

String inputText = "Hello World!";

File.WriteAllText("yourfile.ext",inputText); //writing

var outputText = File.ReadAllText("yourfile.ext"); //reading

있는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★.File,StreamWriter , , , , 입니다.StreamReader②.

언급URL : https://stackoverflow.com/questions/7569904/easiest-way-to-read-from-and-write-to-files

반응형