I have the following problem: i have a string variable, which has to store a filepath. In a foreach loop i go through all files in a certain directory and im looking for the oldest, which is saved in that string variable. When the loop is finished i try to delete that file, but i get an error: Use of an unassigned local variable.
Here is the code:
DateTime min = DateTime.Now;
string[] fileNames = Directory.GetFiles(somePath);
string fileDelete;
int countFiles = fileNames.Length;
if (countfiles > 5)
{
foreach (string someFile in fileNames)
{
FileInfo infoFile = new FileInfo(someFile);
if (infoFile.CreationTime <= min)
{
min = infoFile.CreationTime;
fileDelete = someFile;
}
}
File.Delete(fileDelete);
}
it says that the string fileDelete in File.Delete(fileDelete) has no value, but the fun thin is, when i give it a value at the beginning just like that:
string fileDelete = "blabla";
it works perfectly fine. This is just a snipped of the method in case you are wondering
It works exactly as intended.
In C# local variables are not initialised automatically at declaration.
You're not assinging any value to the fileDelete
when declaring it and assigning it only under some condition in your loop.
But you're trying to use its value outside this condition in loop, thus compiler can't deduce - will fileDelete
has some value at runtime or not (if code under condition will not be executed - then fileDelete
will has no value).
Thus compiler generates this error.