Вла*_*нов 2 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 DirInfo = new DirectoryInfo(dir);
foreach (FileInfo File in DirInfo.GetFiles())
{
FileNames.Add(File.Name);
}
lbFileNames.DataSource = FileNames;
}
Run Code Online (Sandbox Code Playgroud)
在这里,我提取列表框中的所有文件名.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在这里我想做替换,但出了点问题.什么?
听起来你想要更改磁盘上文件的名称.如果是这样,那么您需要使用File.MoveAPI而不是更改实际字符串,即文件名.
你正在犯的另一个错误就是Replace召唤本身.一个string在.NET是不可改变的,因此变异的API都喜欢Replace返回新string主场迎战改变旧的到位.要查看更改,您需要将新值分配回变量
string newName = f.Name.Replace(strReplace, strWith);
File.Move(f.Name, newName);
Run Code Online (Sandbox Code Playgroud)