3333
3333

Reputation: 43

showing list of word files from a directory in the listbox (Asp.net c#)

My code for opening word file from a directory on local machine on a button click event:

    `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);
        }

`

This is showing all word files list in the listbox as my requirement is but also the previously opened temporary word files that is (~$nameoffile.docx) I dont want to display this (~$nameoffile.docx) in the list of list box.

Upvotes: 2

Views: 1375

Answers (1)

Dalorzo
Dalorzo

Reputation: 20014

The files ~$[something].docx are hidden files. What I would recommend you to do is make sure you filter them out like:

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();

The search pattern of dirInf.GetFiles works in the same way the windows does.

This is a Lambda Expression:

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

And this is a bitwise comparison:

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

Upvotes: 1

Related Questions