String 替换C中文件名的一部分#
我有一个包含String 替换C中文件名的一部分#,string,visual-studio-2010,c#-4.0,String,Visual Studio 2010,C# 4.0,我有一个包含.pdf文件的文件夹。在大多数文件的名称中,我想用另一个字符串替换特定的字符串 这是我写的 private void btnGetFiles_Click(object sender, EventArgs e) { string dir = tbGetFIles.Text; List<string> FileNames = new List<string>(); DirectoryInfo DirIn
.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;
}
在这里,我想做替换,但有些地方出了问题。什么?乍一看,似乎您没有将替换的字符串重新分配给f.Name变量。试试这个:
string NewFileName = f.Name.Replace(strReplace, strWith);
File.Copy(f.Name, NewFileName);
File.Delete(f.Name);
替换返回另一个字符串,它不会更改原始字符串。
所以你需要写作
string newName = f.Name.Replace(strReplace, strWith);
当然,这不会更改磁盘上文件的名称。如果这是你的意图,那么你应该看看
File.Move(f.Name, newName);
还要记住,如果目标文件存在,File.Move将失败并出现异常
听起来您想更改磁盘上文件的名称。如果是这样,那么您需要使用
File.Move
API,而不是更改文件名的实际字符串
您正在犯的另一个错误是Replace
调用本身。Net中的string
是不可变的,因此所有的变异API(如Replace
)都返回一个新的string
,而不是将旧的更改到位。要查看更改,需要将新值赋回变量
string newName = f.Name.Replace(strReplace, strWith);
File.Move(f.Name, newName);
f、 名称是只读属性。f、 Name.Replace(..)只返回一个包含所需文件名的新字符串,但不会实际更改文件。
虽然我还没有测试过,但我建议如下:
File.Move(f.Name, f.Name.Replace(strReplace, strWith));
调用
string.Replace
时,这不会改变现有字符串。相反,它返回一个新字符串
您需要将代码更改为以下内容:
if(f.Name.Contains(strReplace))
{
string newFileName = f.Name.Replace(strReplace, strWith);
//and work here with your new string
}
“但有些事情会出问题。什么?”你应该告诉我们出了什么问题(你遇到了什么问题),我们可以帮助你找出解决方法。你还没有这样做。请编辑您的问题,以便实际上有一个问题可以回答。谢谢。你说得对,谢谢你指出这一点。我修改了我的回复。它可以工作:File.Move(dir+@“\”+f.Name,dir+@“\”+f.Name.Replace(strReplace,strWith));抢手货更好的可能是使用Path.Combine
if(f.Name.Contains(strReplace))
{
string newFileName = f.Name.Replace(strReplace, strWith);
//and work here with your new string
}