C#を使ってシンボリックリンクの作成を簡略化する

using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace make_simlink
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string link_address = textBox1.Text.Replace("\"", "");
            string target_address = textBox2.Text.Replace("\"", "");

            bool isDirectory = File.GetAttributes(target_address).HasFlag(FileAttributes.Directory);

            string[] arr = target_address.Split('\\');

            string new_address = link_address + "\\" + arr[arr.Length - 1];

            if (isDirectory)
            {
                var proc = new Process();
                proc.StartInfo.FileName = @"c:\Windows\System32\cmd.exe";
                proc.StartInfo.Verb = "RunAs";
                proc.StartInfo.UseShellExecute = true;
                proc.StartInfo.Arguments = $"/c mklink /d {new_address} {target_address}";
                proc.Start();
            }
            else
            {
                var proc = new Process();
                proc.StartInfo.FileName = @"c:\Windows\System32\cmd.exe";
                proc.StartInfo.Verb = "RunAs";
                proc.StartInfo.UseShellExecute = true;
                proc.StartInfo.Arguments = $"/c mklink {new_address} {target_address}";
                proc.Start();
            }
        }
    }
}



画像生成や動画生成などやっていると扱うファイルのサイズが数GBと大きいことも珍しくありません。

ファイルは一か所に集めているのですが、使う際に毎回絶対パスを書くのは面倒くさいです。

かと言って数GBのファイルを何個も複製するのもためらわれます。

シンボリックリンクを使うことで対応しているのですが、リンクを作成するのにコマンドプロンプトを管理者で実行して、コマンドを打ってとこれまた面倒くさいです。

そこでシンボリックリンクの作成を簡略化するC#コードを書きました。

ファイルやフォルダを選択するためのダイアログはつけていませんが、ファイル(またはフォルダ)のパスをコピーしてテキストボックスに貼り付けるだけです。

追記

テキストボックスにドラッグ&ドロップできるようにするには以下のようにします。

  1. テキストボックスのプロパティで「AllowDrop」を「True」に変更する。
  2. 「DragDrop」と「DragEnter」のイベントを追加する。
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
    if (files != null)
    {
        if (Directory.Exists(files[0]) || File.Exists(files[0])){
            string folderPath = files[0];
            textBox1.Text = folderPath;
        }
    }
}
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
        e.Effect = DragDropEffects.Copy;
    else
        e.Effect = DragDropEffects.None;
}





このエントリーをはてなブックマークに追加