【C#】Windowsでファイル名に使用できない文字を置換する


この記事はプロモーションを含みます。

C#

Windowsのファイル名やフォルダ名に使用できない文字を別の文字に置き換えるメソッドを紹介します。

事前準備

ここでは、事前準備として、ボタンとテキストボックスを配置した簡単な画面を作成します。
ボタンは処理の開始用、テキストボックスは処理時間の表示用です。
以下は、デザインのコードです。

namespace WinFormsApp2
{
    partial class Form1
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            textBox1 = new TextBox();
            button1 = new Button();
            textBox2 = new TextBox();
            SuspendLayout();
            // 
            // textBox1
            // 
            textBox1.Location = new Point(12, 12);
            textBox1.Name = "textBox1";
            textBox1.Size = new Size(164, 23);
            textBox1.TabIndex = 0;
            // 
            // button1
            // 
            button1.Location = new Point(182, 12);
            button1.Name = "button1";
            button1.Size = new Size(75, 50);
            button1.TabIndex = 1;
            button1.Text = "button1";
            button1.UseVisualStyleBackColor = true;
            button1.Click += button1_Click;
            // 
            // textBox2
            // 
            textBox2.Location = new Point(12, 41);
            textBox2.Name = "textBox2";
            textBox2.Size = new Size(164, 23);
            textBox2.TabIndex = 2;
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 15F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(267, 74);
            Controls.Add(textBox2);
            Controls.Add(button1);
            Controls.Add(textBox1);
            Name = "Form1";
            Text = "Form1";
            ResumeLayout(false);
            PerformLayout();
        }

        #endregion

        private TextBox textBox1;
        private Button button1;
        private TextBox textBox2;
    }
}

ソースコード

テキストボックス1に入力した文字列に、Windows環境でファイルやフォルダ名に使用できない文字がある場合は、別の文字に置換するソースコードです。
ソースコード上の「ReplaceInvalidFileNameChars」メソッドで置換処理を行っています。
ここでは例として、半角の記号を全角に置き換えています。

using System.Diagnostics;

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

        private void button1_Click(object sender, EventArgs e)
        {
            textBox2.Text = ReplaceInvalidFileNameChars(textBox1.Text);
        }

        public static string ReplaceInvalidFileNameChars(string oldName)
        {
            string newName;

            newName = oldName.Replace("\\", "¥")
                   .Replace("/", "/")
                   .Replace(":", ":")
                   .Replace("*", "*")
                   .Replace("?", "?")
                   .Replace("\"", "”")
                   .Replace("<", "<")
                   .Replace(">", ">")
                   .Replace("|", "|");

            return newName;
        }
    }
}

実行イメージ

以下は、実行イメージです。

コメント

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