我正在尝试创建一个程序来替换.txt文件中的字符串。 继承人的伎俩。如果选中它们,我将替换文件中的字符串, 但当我做一个替代检查时,它仍然取代了另一个。
private void BatchReplace()
{
string sourceFolder = FilePath.Text;
string searchWord = Searchbar.Text;
DateTime now = DateTime.Now;
List<string> allFiles = new List<string>();
AddFileNamesToList(sourceFolder, allFiles);
if (listView1.CheckedItems.Count != 0)
{
foreach (String file in allFiles)
{
for (int x = 0; x <= listView1.CheckedItems.Count - 1; x++)
{
if (file.Contains(listView1.CheckedItems[x].Text))
{
MessageBox.Show("File contains: " + listView1.CheckedItems[x].Text);
try
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to replace \"" + Searchbar.Text + "\" with \"" + Replacebar.Text + "\"?", "WARNING!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
StreamReader reader = new StreamReader(file);
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace(content, Searchbar.Text, Replacebar.Text);
StreamWriter writer = new StreamWriter(file);
writer.Write(content); writer.Close();
}
else
{
}
}
catch
{
}
}
}
}
}
}
else
{
MessageBox.Show("Please Check the files you want to rename");
}
}
public static void AddFileNamesToList(string sourceDir, List<string> allFiles)
{
string[] fileEntries = Directory.GetFiles(sourceDir);
try
{
foreach (string fileName in fileEntries)
{
allFiles.Add(fileName);
}
//Recursion
string[] subdirectoryEntries = Directory.GetDirectories(sourceDir);
foreach (string item in subdirectoryEntries)
{
// Avoid "reparse points"
if ((File.GetAttributes(item) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
AddFileNamesToList(item, allFiles);
}
}
}
答案 0 :(得分:0)
我仍然对你要做的事情感到困惑,但为了简化事情,为什么不在你用ListView
填充目录中的文件时添加文件路径(或文件) object)到ListViewitem
的标记属性?
这样,当您遍历选中的项目时,您可以直接检索文件,而不必一次遍历两个列表。
类似的东西:
private void BatchReplace()
{
string sourceFolder = FilePath.Text;
string searchWord = Searchbar.Text;
AddFileNamesToList(sourceFolder);
if (listView1.CheckedItems.Count == 0)
{
MessageBox.Show("Please Check the files you want to rename");
return;
}
for (int x = 0; x < listView1.CheckedItems.Count; x++)
{
var file = listView1.CheckedItems[x].Tag.ToString()
try
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to replace \"" + Searchbar.Text + "\" with \"" + Replacebar.Text + "\"?", "WARNING!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
StreamReader reader = new StreamReader(file);
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace(content, SearchWord, Replacebar.Text);
StreamWriter writer = new StreamWriter(file);
writer.Write(content);
writer.Close();
}
}
catch
{
}
}
}
}
对于缩进很抱歉,如果这不能直接工作,我还没有测试过。