ファイル書込み

C#でのファイル書き込み処理について、説明します。

1.手順
 ①ファイルパス設定
 ②ファイルの有無確認
 ③ファイルの書込み

2.コード

// ファイルフルパス設定
string fullpath = @"c:\hoge.txt";

//ファイルの生む確認をします
 if (! System.IO.File.Exists(fullpath ))
 {
        MessageBox.Show("ファイルが存在しません");

        //ファイルを作成する場合の処理 
        using (System.IO.StreamWriter sw = System.IO.File.CreateText(fullpath ))
        {
               //書き込み処理 
               sw.WriteLine("あいうえお");

               //書き込み処理 
                sw.Write("This is the ");

                //閉じる  
                sw.Close();
         }
 }

//※ファイルの有無確認は「File.Exists(fullpath )」でしたが、
//※ディレクトリの有無確認は、Directory.Exists(dirPath)で行います。

//true: 追記 / false:上書き 
appendflg = false;   

//文字コードをシフトJISにします。
System.Text. Encoding   encoder =  Encoding.GetEncoding("Shift_JIS")

//ファイルストリームインスタンスを生成(ファイルパス 、書き込みモード 、エンコード  )
System.IO. StreamWriter sw = new StreamWriter(fullPath,  appendflg ,  encoder  );

//書き込み処理 
sw.WriteLine("あいうえお");

//書き込み処理 
sw.Write("This is the ");

//閉じる 
sw.Close();

コメント