January 16th, 2011 04:09 PM
#1
[RESOLVED] FileInfo look up problems
Getting the most subtle error took me forever to narrow it down, now that I found it I don't know what to do
so here's the deal: I want to read into a Directory and load a file from the directory
here are the files
Armor_Cloth_clothes.xml
Armor_Leather_leather.xml
Armor_Leather_lightleather.xml
Armor_Padded_padded.xml
this is the code I'm using
Code:
private void LookForFile(string armorName)
{
string directory = itemsContentPath + @"\Armor\";
string armor = armorName.Replace(" ", "");
string armorLowered = armor.ToLower();
DirectoryInfo dir = new DirectoryInfo(directory);
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
if (file.Name.Contains(armorLowered))
{
string thisArmor = directory + file.Name;
ReadArmor(thisArmor);
}
}
}
the problem is here >> if (file.Name.Contains(armorLowered))
if I ask for "Clothes", then "Light Leather", then "Leather", and finally "Padded"
I should have an output of Clothes, Leather, Light Leather, Padded, but instead I'm getting
Clothes, Light Leather, Light Leather, Padded
January 16th, 2011 04:21 PM
#2
Re: [RESOLVED] FileInfo look up problems
Figured it out, realized I needed to parse out file to make a better comparison
Code:
private void LookForFile(string armorName)
{
string directory = itemsContentPath + @"\Armor\";
string armor = armorName.Replace(" ", "");
string armorLowered = armor.ToLower();
DirectoryInfo dir = new DirectoryInfo(directory);
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string filename = Convert.ToString(file);
var wordsWithLowercase = filename.Split('_').Where(word => char.IsLower(word[0])).Distinct();
string truncated = string.Join("", wordsWithLowercase.ToArray());
string item = truncated.Replace(".xml", "");
if (item == armorLowered)
{
string thisArmor = directory + file.Name;
ReadArmor(thisArmor);
}
}
}
January 19th, 2011 07:36 AM
#3
Re: [RESOLVED] FileInfo look up problems
I didn't test anything, but couldn't you go somewhere along these lines?string armorLowered = armorName.Replace(" ", "_").ToLower();
// then later...
string filename = Path.GetFileNameWithoutExtension(file.FullName).ToLower();
if (armorLowered == filename) //...
Even better, you could use the File.Exists(string path) static method to avoid the loop completely. If there's a chance for multiple files to be returned (but it doesn't look like it), you could use the GetFiles(...) method of the DirectoryInfo class.
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Click Here to Expand Forum to Full Width
Bookmarks