質問

/ images / graphicsLib /にあるディレクトリ内のいくつかの画像の名前を変更するには、助けが必要です。

/ graphicsLib /のすべての画像名には、次のような命名規則があります。 400-60947.jpg。 「400」を呼び出しますファイルの一部にプレフィックスを付け、「60957」を呼び出します。接尾辞を分けます。 skuと呼ぶファイル名全体。

したがって、/ graphicLib /の内容を見た場合、次のようになります。
400-60957.jpg
400-60960.jpg
400-60967.jpg
400-60968.jpg
402-60988.jpg
402-60700.jpg
500-60725.jpg
500-60733.jpg
など...

C#の使用& System.IO、ファイル名のプレフィックスに基づいてすべての画像ファイルの名前を変更するための受け入れ可能な方法は何ですか?ユーザーは、現在のプレフィックスを入力し、一致する/ graphicsLib /内のすべての画像を表示し、新しいプレフィックスを入力して、すべてのファイルの名前を新しいプレフィックスで変更できるようにする必要があります。ファイルのプレフィックスのみが名前変更され、残りのファイル名は変更する必要がありません。

これまでのところ:

//enter in current prefix to see what images will be affected by
// the rename process,
// bind results to a bulleted list.
// Also there is a textbox called oldSkuTextBox and button
// called searchButton in .aspx


private void searchButton_Click(object sender, EventArgs e)

{

string skuPrefix = oldSkuTextBox.Text;


string pathToFiles = "e:\\sites\\oursite\\siteroot\\images\graphicsLib\\";  

string searchPattern = skuPrefix + "*";

skuBulletedList.DataSource = Directory.GetFiles(pathToFiles, searchPattern);

skuBulletedList.DataBind();

}



//enter in new prefix for the file rename
//there is a textbox called newSkuTextBox and
//button called newSkuButton in .aspx

private void newSkuButton_Click(object sender, EventArgs e)

{

//Should I loop through the Items in my List,
// or loop through the files found in the /graphicsLib/ directory?

//assuming a loop through the list:

foreach(ListItem imageFile in skuBulletedList.Items)

{

string newPrefix  = newSkuTextBox.Text;

//need to do a string split here?
//Then concatenate the new prefix with the split
//of the string that will remain changed?

 }

}
役に立ちましたか?

解決

string.Split をご覧ください。 。

ディレクトリ内のすべてのファイルをループします。

string[] fileParts = oldFileName.Split('-');

これにより、2つの文字列の配列が得られます。

fileParts[0] -> "400"
fileParts[1] -> "60957.jpg"

リストの名を使用します。

新しいファイル名は次のようになります。

if (fileParts[0].Equals(oldPrefix))
{
    newFileName = string.Format("(0)-(1)", newPrefix, fileParts[1]);
}

次に、ファイルの名前を変更します:

File.Move(oldFileName, newFileName);

ディレクトリ内のファイルをループするには:

foreach (string oldFileName in Directory.GetFiles(pathToFiles, searchPattern))
{
    // Rename logic
}

他のヒント

実際には、ディレクトリ内の各ファイルを反復処理し、1つずつ名前を変更する必要があります

新しいファイル名を決定するには、次のようなものを使用できます:

String newFileName = Regex.Replace("400-60957.jpg", @"^(\d)+\-(\d)+", x=> "NewPrefix" + "-" + x.Groups[2].Value);

ファイルの名前を変更するには、次のようなものを使用できます:

File.Move(oldFileName, newFileName);

正規表現に慣れていない場合は、次を確認する必要があります。 http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx

このソフトウェアを実際にダウンロードしてください: http://www.radsoftware.com.au/regexdesigner/

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top