I am checking if a file exists, and if it does, I put it in a list, otherwise I remove from the list. My code is so:
foreach (KeyValuePair<string, string> kvp in dict)
{
_savedxml.Add(kvp.Key.ToString());
}
string namewithext=null;
for (int i = 0; i < _savedxml.Count; i++)
{
namewithext = string.Concat(_savedxml[i], ".xml");
System.IO.FileInfo file_info = new System.IO.FileInfo((string)namewithext);
long size = file_info.Length;
if (size == 0)
{
_savedxml.RemoveAt(i);
}
}
for (int i = 0; i < _savedxml.Count; i++)
{
if (System.IO.File.Exists(System.IO.Path.GetFullPath(namewithext)))
{
}
else
{
_savedxml.Remove(namewithext);
}
}
I’ve tried many ways, but even though a file does not exist, the list contains it. I’ve probably made a silly error.
How can I do this?
There are several errors in the code:
You set the
namewithextvariable for each item in the first loop, then use it in the second loop, so you will be checking if the last file exist over and over.When you remove an item, the next item takes its place in the list, so you will skip the check for the next item.
You are checking the length of the files before checking if the files exist, so you will get a
FileNotFoundExceptionwhen you try to get the length for files that doesn’t exist.Corrected (and some cleanup):