[英]Replacing Matching File Names in String List
I have a main List of Files Filelist
.The Main List Contains Full File Paths and there is a second list copylist
it is poupulated by fetching the contents from a directory.I need to replace the File Names in Filelist
that matches with the ones in the temporary folder,so i used the following code.我有一个主文件列表Filelist
。主列表包含完整文件路径,还有第二个列表copylist
列表,它是通过从目录中获取内容来填充的。我需要替换Filelist
中与文件名中的文件名匹配的文件名临时文件夹,所以我使用了以下代码。
Filelist = new List<string>();
//Code to Populate File List from openfiledialog
try
{
copylist = Directory.GetFiles(temppath + @"\mydir\");
List<string> tempfiles = new List<string>(Filelist);
int x = 0;
foreach (string file in tempfiles)
{
for (int i = 0; i < copylist .Length; i++)
{
if (Path.GetFileName(file) == Path.GetFileName(copylist [i]))
{
MessageBox.Show("Removed: " + file + " \ninserted:" + copylist [i]);
Filelist.RemoveAt(x);
Filelist.Insert(x,copylist [i]);
}
x++;
}
}
}
catch (Exception)
{
}
I tested with 4 files... The File names matched when i checked manually(ie: the same file name in temp folder and in the FileList).The equality check ie: Path.GetFileName(file) == Path.GetFileName(copylist [i])
is satisfied for just 2 files and finally only 1 file is replaced in Filelist
even though all 4 files are present in temp folder.我测试了 4 个文件......我手动检查时文件名匹配(即:临时文件夹和 FileList 中的相同文件名)。相等性检查即: Path.GetFileName(file) == Path.GetFileName(copylist [i])
仅对 2 个文件感到满意,即使所有 4 个文件都存在于临时文件夹中,但最终只有 1 个文件在Filelist
被替换。
What im i doing wrong.Please advice.我做错了什么。请指教。
The logic of your program relies on the fact that positions in tempfiles
and Filelist
are related, and that x
corresponds to the position of file
in tempfiles
.程序的逻辑依赖于tempfiles
和Filelist
位置相关的事实,并且x
对应于tempfiles
中file
的位置。 In order for this to work you need to add a break
inside the if
, and move x++
to the outside loop:为了使其工作,您需要在if
内添加一个break
,并将x++
移动到外部循环:
foreach (string file in tempfiles) {
for (int i = 0; i < copylist .Length; i++) {
if (Path.GetFileName(file) == Path.GetFileName(copylist [i])) {
MessageBox.Show($"Removed: {file}\ninserted:{copylist [i])}";
Filelist.RemoveAt(x);
Filelist.Insert(x,copylist[i]);
break; // << Added
}
}
x++; // << Moved
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.