开发者

Problem with Regex.Replace() while changing a filename

I am having a strange problem and I can't seem to figure it out.

My filename is something like this:

DER 1513016-3.020F.NCF.

I want to be able to change it to:

DER 1513016-3.020H.NCF

Sometimes the filename can be this as well:

DER 1513016-3.020F_NEW.NCF

which would change to:

DER 1513016-3.020H_NEW.NCF

This is my code to do this:

OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Open";
fDialog.Filter = "NCF files (*.ncf)|*.ncf|All files (*.*)|*.*";
fDialog.InitialDirectory = "C:\\Program Files";
if (fDialog.ShowDialog() == DialogResult.OK)
{
    string newfilename;
    string fileext = Path.GetExtension(fDialog.FileName);

    newfilename = Regex.Replace(fDialog.FileName, "F.NCF", "H.NCF");
    newfilename = Regex.Replace(fDialog.FileName, "F_NEW.NCF", "H_NEW.NCF");
} 

This is where things get weird. The way the code works now, it will NOT change the filename to DER 1513016-3.020H.NCF

If I comment out this line of code:

//newfilename = Regex.Replace(fDialog.FileName, "F_NEW.NCF", "H_NEW.NCF");

it will work fine and the file will now become: DER 1513016-3.020H.NCF

However,开发者_如何学C if I uncomment that line of code, the filename will not change to DER 1513016-3.020H.NCF. It will stay as DER 1513016-3.020F.NCF.

Why is that line of code causing the routine to not change the filename?


Use newfilename instead of fDialog.FileName on the second call or the return value of the first one will never be used.

PS: You can use String.Replace instead of Regex.Replace since you're not using any regular expressions. Plus, the dot means "any character" in a regex so you should consider escaping it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜