ファイル/フォルダの作成/削除/コピー/移動/名前変更

簡単に説明します。

ファイルの作成/削除/コピー/移動/名前変更

ファイルの作成

ファイルの作成は、単純なテキストの出力は以下でできます。

string file_path = @"d:\temp\sample.txt";
string write_text = "sample text";

System.IO.File.WriteAllText(file_path, write_text, System.Text.Encoding.GetEncoding("shift_jis"));

ファイルの削除

ファイルがある場合、削除します。
Deleteメソッドを試したところ、ファイルがなくてもエラーになりませんでした。ただいつか仕様が変わってファイルがない場合は、例外になるというのも考えられるのでファイルがない場合は処理しないようにしておくほうが吉だと思います。

string file_path = @"d:\temp\sample.txt";

if (System.IO.File.Exists(file_path) == true)
{
    System.IO.File.Delete(file_path);
}

ファイルのコピー

ファイルのコピーもコピー元のファイルがあること、コピー先にファイルがないことが前提なのでファイル存在チェックをしてます。

string src_file_path = @"d:\temp\sample.txt";
string dest_file_path = @"d:\work\sample.txt";

if (System.IO.File.Exists(src_file_path) == true &&
    System.IO.File.Exists(dest_file_path) == false)
{
    System.IO.File.Copy(src_file_path, dest_file_path);
}

ファイルの移動

ファイルの移動も元のファイルがあること、移動先にファイルがないことが前提なのでファイル存在チェックをしてます。

string src_file_path = @"d:\temp\sample.txt";
string dest_file_path = @"d:\work\sample.txt";

if (System.IO.File.Exists(src_file_path) == true &&
    System.IO.File.Exists(dest_file_path) == false)
{
    System.IO.File.Move(src_file_path, dest_file_path);
}

ファイルの名前変更

ファイルの名前を変えるのはMoveメソッドでできます。

string src_file_path = @"d:\temp\sample.txt";       //名前変更するファイル
string dest_file_path = @"d:\temp\rename.txt";      //変更後の名前のファイル

if (System.IO.File.Exists(src_file_path) == true &&
    System.IO.File.Exists(dest_file_path) == false)
{
    System.IO.File.Move(src_file_path, dest_file_path);
}

ファイル名を変更する関数を作成してみました。(オマケ)

/// <summary>
/// ファイル名の変更
/// </summary>
/// <param name="file">名前を変更するファイル</param>
/// <param name="new_file_name">新しいファイルの名前</param>
/// <returns></returns>
private bool RenameFile(string file, string new_file_name)
{
    //変更後の名前のファイルパス
    string rename_file_path = string.Format("{0}\\{1}", System.IO.Path.GetDirectoryName(file), new_file_name);     

    if (System.IO.File.Exists(file) == false) return false;    //変更元のファイルがない場合はfalse
    if (System.IO.File.Exists(rename_file_path) == true) return false;    //変更先のファイルがある場合はfalse

    //名前の変更
    System.IO.File.Move(file, rename_file_path);

    return true;
}
使い方例
if (RenameFile(@"d:\temp\rename.txt", "sample.txt") == false)
{
    MessageBox.Show("失敗");
}

MessageBox.Show("成功");

フォルダの作成/削除/コピー/移動/名前変更

フォルダの作成

string dir_path = @"d:\temp\SampleDir";

//フォルダチェック
if (System.IO.Directory.Exists(dir_path) == false)
{
    //なかったら新しく作成
    System.IO.Directory.CreateDirectory(dir_path);
}

フォルダの削除

Delete関数の第2引数は、trueで中のファイルも削除します。デフォルトはfalseで中のファイルを削除しないことに注意です。

string file_path = @"d:\temp\SampleDir";

if (System.IO.Directory.Exists(file_path) == true)
{
    System.IO.Directory.Delete(file_path, true);
}

フォルダのコピー

フォルダのコピーに関するメソッドはありませんでしたので関数を作成しました。

/// <summary>
/// フォルダをコピーする
/// </summary>
/// <param name="src_dir">コピー元フォルダ</param>
/// <param name="dest_dir">コピー先フォルダ</param>
/// <param name="file_copy">フォルダ内のファイルコピーするか(true/false)- default:true</param>
/// <param name="overwrite">フォルダがある場合、上書きするか(true/false)- default:true</param>
/// <returns>
///     success:true
///     failed:false
/// </returns>
private bool CopyDirectory(string src_dir, string dest_dir, bool file_copy = true, bool overwrite = true)
{
    if (System.IO.Directory.Exists(src_dir) == false) return false;    //コピー元のフォルダがない場合はfalse

    //コピー先のフォルダがない場合は、作成false
    if (System.IO.Directory.Exists(dest_dir) == false)
    {
        //コピー先のフォルダを作成
        System.IO.Directory.CreateDirectory(dest_dir);
    } else
    {
        //上書き禁止の場合は、コピーしない
        if (overwrite == false) return false;
    }

    //ファイルコピーしない場合は、終了
    if (file_copy == false) return true;

    //コピー元フォルダ内のファイルコピー
    foreach(string file in System.IO.Directory.GetFiles(src_dir))
    {
        string dest_file = string.Format("{0}\\{1}", dest_dir, System.IO.Path.GetFileName(file));

        System.IO.File.Copy(file, dest_file, true);
    }

    return true;
}

使うには以下のようにします。

string src_dir_path = @"d:\temp\SampleDir";
string dest_dir_path = @"d:\temp\CopyDir";

if (CopyDirectory(src_dir_path, dest_dir_path) == false)
{
    MessageBox.Show("コピー失敗");
    return;
}

フォルダの移動

string src_dir_path = @"d:\temp\SampleDir";
string dest_dir_path = @"d:\work\SampleDir";


if (System.IO.File.Exists(src_dir_path) == true &&
    System.IO.File.Exists(dest_dir_path) == false)
{

    //フォルダの移動
    System.IO.Directory.Move(src_dir_path, dest_dir_path);
}

  

このMove関数ですが、移動先にフォルダがある場合エラーになります。なのでフォルダのコピーで紹介したコピー関数を使ってやるのよいかと思います。

string src_dir_path = @"d:\temp\SampleDir";
string dest_dir_path = @"d:\work\SampleDir";

//コピー
if (CopyDirectory(src_dir_path, dest_dir_path) == false)
{
    MessageBox.Show("移動失敗");
    return;
}

//削除
System.IO.Directory.Delete(src_dir_path, true);

フォルダの名前変更

名前の変更もファイルの時と同じで移動を利用します。

string src_dir_path = @"d:\temp\SampleDir";
string dest_dir_path = @"d:\temp\CopyDir";

if (System.IO.File.Exists(src_dir_path) == true &&
    System.IO.File.Exists(dest_dir_path) == false)
{
    System.IO.Directory.Move(src_dir_path, dest_dir_path);
}

先ほど移動のところでも説明した通り同じフォルダが存在すると変更できません。
同様にコピーする関数を使ってみます。

string src_dir_path = @"d:\temp\SampleDir";
string dest_dir_path = @"d:\temp\CopyDir";

//コピー
if (CopyDirectory(src_dir_path, dest_dir_path) == false)
{
    MessageBox.Show("名前変更失敗");
    return;
}

//削除
System.IO.Directory.Delete(src_dir_path, true);

まとめ

ファイルの存在チェックなどなるべく実際の関数利用する際に注意しておきたいところもソースに入れてみました。

この記事が皆様のお役に立てば幸いです。

コメント

タイトルとURLをコピーしました