2012-05-07 30 views
1

人。C#のファイル名の一部を置き換えます。

私には.pdfファイルのフォルダがあります。ほとんどのファイルの名前で、特定の文字列を別の文字列に置き換えたい。私は、リストボックス内のすべてのファイル名を抽出する。ここ

private void btnGetFiles_Click(object sender, EventArgs e) 
    { 
     string dir = tbGetFIles.Text; 
     List<string> FileNames = new List<string>(); 

     DirectoryInfo DirInfo = new DirectoryInfo(dir); 

     foreach (FileInfo File in DirInfo.GetFiles()) 
     { 
      FileNames.Add(File.Name);  
     } 

     lbFileNames.DataSource = FileNames; 
    } 

:この時点で私はこれを書きました。

private void btnReplace_Click(object sender, EventArgs e) 
    { 
     string strReplace = tbReplace.Text; // The existing string 
     string strWith = tbWith.Text; // The new string 

     string dir = tbGetFIles.Text; 
     DirectoryInfo DirInfo = new DirectoryInfo(dir); 
     FileInfo[] names = DirInfo.GetFiles(); 


     foreach (FileInfo f in names) 
     { 
      if(f.Name.Contains(strReplace)) 
      { 
       f.Name.Replace(strReplace, strWith); 
      } 

     } 

ここで私は置き換えたいですが、何かが間違っています。何?

+0

あなたは何がうまくいかなかったか(あなたが抱えている問題)を教えてくれると思います。それを修正する方法を理解するのを手助けすることができます。あなたはそうしていません。 **実際に**答えられる質問があるようにあなたの質問を編集してください。ありがとう。 :) –

+0

[置換は置き換えません。リターンを返す](http://stackoverflow.com/questions/1948978/string-replace-not-working)。 – GSerg

答えて

4

あなたはディスク上のファイルの名前を変更したいように聞こえます。その場合は、File.Move APIとファイル名である実際の文字列を変更する必要があります。

もう1つの間違いは、Replace呼び出しです。 .Netのstringは不変なので、Replaceのようなすべての変更APIは新しいものを返します。これに対して、古いものを変更するのは新しいstringです。変更を確認するには、変数

string newName = f.Name.Replace(strReplace, strWith); 
File.Move(f.Name, newName); 
0

一見すると、置き換えられた文字列をf.Name変数に再割り当てしていないようです。これを試してみてください:

string NewFileName = f.Name.Replace(strReplace, strWith); 
File.Copy(f.Name, NewFileName); 
File.Delete(f.Name); 
+1

f.Nameは読み取り専用です –

+0

あなたは正しく、それを指摘してくれてありがとうございます。私は自分の返信を修正しました。 –

1

別の文字列を返すに置き換え、それは元の文字列を変更しません。
だから、これは、ディスク上のファイルの名前を変更しませんもちろんの

string newName = f.Name.Replace(strReplace, strWith); 

を記述する必要があります。
それはあなたの意図だった場合、あなたはまた、先のファイルが存在する場合File.Moveは例外で失敗することに注意してください

File.Move(f.Name, newName); 

をご覧ください。

See here for an example

2

f.Nameに戻って、新しい値を割り当てる必要があることは、読み取り専用のプロパティです。 f.Name.Replace(..)は、単にファイル名を指定して新しい文字列を返しますが、実際にはファイルを変更することはありません。
私はそれをテストしていないものの、次のように沿って何かをお勧め:

File.Move(f.Name, f.Name.Replace(strReplace, strWith)); 
+1

作品: File.Move(dir + @ "\" + f.Name、dir + @ "\" + f.Name.Replace(strReplace、strWith)); –

+0

良いキャッチ。おそらくPath.Combineを使用する方が良いでしょう –

0

あなたはこれがあなたの既存の文字列を変更しませんstring.Replaceを呼び出すとき。代わりに新しい文字列を返します。

あなたはこのような何かにあなたのコードを変更する必要があります「しかし、何かが間違っgones何を?」

if(f.Name.Contains(strReplace)) 
{ 
    string newFileName = f.Name.Replace(strReplace, strWith); 
    //and work here with your new string 
} 
関連する問題