I have this code where you are suppose to be able to pick specific file attributes, but for some reason it is acting really weird. Can anyone spot the error(s)?
This is in a form, I am triggering checkAttributes when a file is selected. (string)path is the path to the selected file.
private async void Dropdown_File_Attr_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
try
{
foreach (FileAttributes attr in Enum.GetValues(typeof(FileAttributes)))
if (e.ClickedItem.Text == attr.ToString() && !(bool)e.ClickedItem.Tag)
File.SetAttributes(path, File.GetAttributes(path) | attr);
else if (e.ClickedItem.Text == attr.ToString() && (bool)e.ClickedItem.Tag)
File.SetAttributes(path, File.GetAttributes(path) & ~attr);
checkAttributes(path);
await WaitX(5);
Dropdown_File.ShowDropDown();
Dropdown_File_Attr.ShowDropDown();
}
catch (Exception ex) { MessageBox.Show("An error occured:\n\n" + ex.ToString(), "Error"); }
}
public async Task WaitX(int miliseconds) { await Task.Delay(miliseconds); }
private List<string> getAttributes(string ppath)
{
List<string> result = new List<string>();
FileAttributes attrs = File.GetAttributes(ppath);
if ((attrs & FileAttributes.Archive) == FileAttributes.Archive) result.Add("Archive");
if ((attrs & FileAttributes.Compressed) == FileAttributes.Compressed) result.Add("Compressed");
// This goes on for every attribute
return result;
}
private void checkAttributes(string ppath)
{
foreach (string s in getAttributes(ppath))
foreach (ToolStripDropDownItem item in Dropdown_File_Attr.DropDownItems)
{
if (item.Text == s)
{
item.Image = Resources.check;
item.Tag = true; // isChecked
}
else
{
item.Image = Resources.cross;
item.Tag = false; // isChecked
}
}
}
Just an example:
If in the beginning only Normal is selected, and I select Hidden, Hidden is the only one with a cross. If then select ReadOnly, ReadOnly is the only one with a cross but if I check, the file is still Hidden in Windows Explorer.
I have been looking for the error hours. Can anyone please help me (I don't have a lot of experience with Enums and FileAttributes)?
you loop over all items of the dropdown, but act only on the clicked item. you have to check all of the items. and combine their values to construckt the final attribute value, or you'll never catch the automatically cleared item. or just set the one checked attribute, without combining it with the current flags of the file, id you only want to set the one anyway.
as an aside, your logic would work with multi selection, which i'd allow anyway. it makes sense to allow setting a file hidden and readonly, for example.