c# - 在列表框中显示目录中的单词文件列表 (Asp.net c#)

标签 c# asp.net io listbox directory

我在按钮单击事件中从本地计算机上的目录打开 word 文件的代码:

    `string path = @"C:\Users\Ansar\Documents\Visual Studio 2010\Projects\GoodLifeTemplate\GoodLifeTemplate\Reports\IT";
    List<string> AllFiles = new List<string>();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ParsePath();
        }
    }
    void ParsePath()
    {
        string[] SubDirs = Directory.GetDirectories(path);
        AllFiles.AddRange(SubDirs);
        AllFiles.AddRange(Directory.GetFiles(path));
        int i = 0;
        foreach (string subdir in SubDirs)
        {
            ListBox1.Items.Add(SubDirs[i].Substring(path.Length + 1, subdir.Length - path.Length - 1).ToString());

            i++;
        }

        DirectoryInfo d = new DirectoryInfo(path);
        FileInfo[] Files = d.GetFiles("*.doc")
        ListBox1.Items.Clear();
        foreach (FileInfo file in Files)
        {
            ListBox1.Items.Add(file.ToString());
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (ListBox1.SelectedItem != null)
        {
            Microsoft.Office.Interop.Word.Application ap = new Microsoft.Office.Interop.Word.Application();
            Document document = ap.Documents.Open(path + "\\" + ListBox1.SelectedItem.Text);
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "error", "Please select file;", true);
        }

`

这显示了列表框中的所有单词文件列表,因为我的要求是,但也显示了以前打开的临时单词文件 (~$nameoffile.docx) 我不想显示这个 (~$nameoffile.docx) 在列表框的列表中。

最佳答案

文件 ~$[something].docx 是隐藏文件。我建议您做的是确保像这样过滤掉它们:

System.IO.DirectoryInfo dirInf = new System.IO.DirectoryInfo(@"C:\myDir\Documents");
var files = dirInf.GetFiles("*.doc").Where(f => (f.Attributes & System.IO.FileAttributes.Hidden) != System.IO.FileAttributes.Hidden).ToArray();

dirInf.GetFiles 的搜索模式与 Windows 的工作方式相同。

这是一个 Lambda Expression :

.Where(f => (f.Attributes & System.IO.FileAttributes.Hidden) != System.IO.FileAttributes.Hidden)

这是一个 bitwise comparison :

(f.Attributes & System.IO.FileAttributes.Hidden) != System.IO.FileAttributes.Hidden

关于c# - 在列表框中显示目录中的单词文件列表 (Asp.net c#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21071845/

相关文章:

c# - 验证不适用于动态 @Html.DropDownListFor

c# - MenuItem 事件未在 asp.net 菜单中触发

events - 非阻塞(事件驱动 I/O)与阻塞 I/O

c - I/O 到屏幕/标准输出

c# - 检查用户输入是真还是假

c# - 以编程方式在 DataGridView 中设置列​​宽

c# - Windows Azure 上的 ASP.NET MVC 4 session 10 分钟后过期

c# - 以 DataTable 作为源的 GridView 不自动分页或排序

asp.net - 我如何使用asp.net MVC4隐藏URL中的ID

java - 打开的文件句柄太多