Reputation: 13
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
Upvotes: 1
Views: 1902
Reputation: 72
Use this
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);
}
}
}
Upvotes: 0
Reputation: 463
You must initialize your variable. see at Why compile error "Use of unassigned local variable"?
Upvotes: 0
Reputation: 26846
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.
Upvotes: 1
Reputation: 9733
in C# you have to initialise variables, otherwise you could pass garbage values to File.Delete.
I recommend using
string fileDelete = null; // or ""
and later check for that.
if (!string.IsNullOrEmpty(fileDelete))
{
File.Delete(fileDelete);
}
Upvotes: 3
Reputation: 6463
Imagine this scenario:
countFiles > 5
is TrueinfoFile
for someFile
is bigger than min
What value will fileDelete
have when passed to File.Delete
?
Answer: In such scenario fileDelete
will be uninitialized, thus the error message.
Upvotes: 0