web-dev-qa-db-ja.com

ファイルを読み書きする最も簡単な方法

C#でファイル( テキストファイル 、バイナリではない)を読み書きするにはさまざまな方法があります。

私は自分のプロジェクトでファイルを使って作業することになるので、簡単で最小限のコードを使用するものが必要です。必要なのはstringを読み書きするだけなので、私はstringに必要なものだけです。

284

File.ReadAllText および File.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);
457
vc 74

別の回答 に示されているFile.ReadAllTextFile.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 readMeText = readtext.ReadLine();
}

ノート:

  • using の代わりに readtext.Close() を使用することができますが、例外の場合はファイル/リーダー/ライターを閉じません。
  • 相対パスは現在の作業ディレクトリからの相対パスです。絶対パスを使用/構築することができます。
  • using/Closeがないのは、「ファイルにデータが書き込まれていない理由」の一般的な理由です。
141
Bali C
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");
    }
}
16
Swapnil
using (var file = File.Create("pricequote.txt"))
{
    ...........                        
}

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

あなたがそれを終えたら、シンプルで、簡単で、そしてまた、オブジェクトを処分/浄化します。

10
Ankit Dass

ファイルから読み込んでファイルに書き込む最も簡単な方法:

//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);
}
9
yazarloo

@AlexeiLevenkovは、もう1つの "最も簡単な方法"、つまり 拡張方法 を私に指摘しました。それはほんの少しのコーディングを必要とし、それから読み書きするための絶対に最も簡単な方法を提供し、さらにそれはあなたの個人的な必要性に従ってバリエーションを作成する柔軟性を提供します。これが完全な例です。

これはstring型の拡張メソッドを定義します。本当に重要なのは、追加のキーワードthisを持つ関数の引数だけです。これは、メソッドが関連付けられているオブジェクトを参照するためのものです。名前空間とクラスの宣言はオプションです。

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

私はこれを自分で見つけることはなかったでしょうが、それは素晴らしい作品ですので、私はこれを共有したいと思いました。楽しむ!

8
Roland

あるいは、あなたが本当にラインについてであれば:

System.IO.Fileには静的メソッド WriteAllLines も含まれています。

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

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

OpenFileDialogコントロールを使用して、読みたいファイルを参照することをお勧めします。以下のコードを見つけてください。

ファイルを読み取るために次のusingステートメントを追加することを忘れないでください。using System.IO;

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

ファイルを書くためには、メソッドFile.WriteAllTextを使うことができます。

3
SamekaTV

これらはファイルに読み書きするための最良かつ最も一般的に使用される方法です。

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インポートステートメントを含めてください)、使用可能なすべてのメソッドを確認してください。以下は、Windowsフォームアプリケーションを使用してテキストファイル(.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
}
3
technoman23
     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);
        }      
    }

FileStreamWriter、およびStreamReaderクラスを探しています。

0
SLaks