1

我有这段代码,您应该可以在其中选择特定的文件属性,但由于某种原因,它的行为真的很奇怪。任何人都可以发现错误吗?

这是一种形式,我在选择文件时触发 checkAttributes。(string)path 是所选文件的路径。

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
            }
         }
}

只是一个例子:

如果一开始只选择了 Normal,而我选择了 Hidden,那么 Hidden 是唯一一个带叉号的。如果然后选择 ReadOnly,ReadOnly 是唯一一个带有叉号的,但如果我检查,该文件仍然隐藏在 Windows 资源管理器中。

我一直在寻找错误时间。谁能帮帮我(我对枚举和文件属性没有很多经验)?

4

1 回答 1

1

您循环遍历下拉列表的所有项目,但仅对单击的项目执行操作。你必须检查所有的项目。并结合它们的值来构造最终的属性值,否则您将永远无法捕捉到自动清除的项目。或者只设置一个选中的属性,而不将它与文件的当前标志结合起来,id 你只想设置一个。

顺便说一句,您的逻辑将适用于多选,无论如何我都会允许。例如,允许将文件设置为隐藏和只读是有意义的。

于 2014-09-19T19:08:01.430 回答