Найдите и проанализируйте файлы на подключенном сетевом диске C# Windows Форма - PullRequest
0 голосов
/ 06 мая 2020

Я пишу простую программу для поиска всех файлов с заданными расширениями, которые содержат заданные пользователем ключевые слова на сервере sharepoint.

Обычно мы подключаемся к этому серверу, используя подключенный сетевой диск, и я был в надежде использовать тот же метод в моем приложении. Однако, используя то, что я сделал в настоящее время, пользователи не могут просматривать и выбирать подключенный диск в качестве каталога root для поиска. Я пытаюсь использовать FolderBrowserDialog, чтобы позволить пользователям выбирать желаемый каталог поиска, но, как я уже сказал, подключенный диск не отображается в диалоговом окне, и даже ввод каталога вручную не работает и не вводится путь к серверу, т.е. \ server \ sub \ dir.

Остальная часть моего кода делает то, что я хочу, с локальными файлами. Как я могу предоставить своему приложению доступ к файлам, расположенным на сервере?

Код приложения:

using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DispositionReportParser
{
    public partial class Form1 : Form
    {
        private readonly SynchronizationContext synchronizationContext;
        private DateTime previousTime = DateTime.Now;
        private List<String> filetypes = new List<String>();

        public Form1()
        {
            InitializeComponent();

            synchronizationContext = SynchronizationContext.Current; //context from UI thread
        }

        private void btnSelectRootDirectory_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbDialog = new FolderBrowserDialog();
            DialogResult result = fbDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                txtRootDirectory.Text = fbDialog.SelectedPath;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (txtRootDirectory.Text == "" || !Directory.Exists(txtRootDirectory.Text))//This condition is always met when manually placing the network path in the txtRootDirectory textbox, and removing the Exists() check causes errors of 'Directory not found' later in the code.
            {
                MessageBox.Show("Root directory is invalid. Please enter a valid directory.");
            }
            else if (txtKeywords.Text == "")
            {
                MessageBox.Show("No keywords entered. You need at least one keyword to search for.");
            }
            else
            {
                Search();               
             }
        }       

        private async void Search()
        {
            lstResults.Items.Clear();
            List<string> result = new List<string>();
            List<String> matchingFiles = new List<String>();
            await Task.Run(() =>
            {
                UpdateUI("Parsing keywords...");


                UpdateUI("Searching for files...");
                string directoryToSearch = txtRootDirectory.Text;
                //string[] foundFiles = Directory.GetFiles(directoryToSearch, "*.txt", SearchOption.AllDirectories);


                foreach (string file in Directory.EnumerateFiles(directoryToSearch, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".csv")
                || s.EndsWith(".xsl") || s.EndsWith(".xsxl") || s.EndsWith(".xlsm") || s.EndsWith(".xlsb") || s.EndsWith(".xltx")))
                {
                    result.Add(file);
                }

                UpdateUI("Parsing Files...");
                String[] keywords = txtKeywords.Text.Split(',');

                foreach (string file in result)
                {
                    string fileContents = File.ReadAllText(file).ToLower(); //This breaks when it doesn't have file permissions. Try to find a way around that. 
                    foreach(string keyword in keywords)
                    {
                        if (fileContents.Contains(keyword.ToLower()))
                        {
                            matchingFiles.Add(file);
                            UpdateUI("Found file: " + file);
                            break;
                        }
                    }
                }
            });  

            foreach(String filename in matchingFiles)
            {
                lstResults.Items.Add(filename);
            }

            UpdateUI("Complete!");
        }

        public void UpdateUI(string value)
        {
            //Send the update to our UI thread  
            synchronizationContext.Post(new SendOrPostCallback(o =>
            {
                lblProcessInfo.Text = value;
            }), value);

        }

        private void lstResults_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        public static void OpenWithDefaultProgram(string path)
        {
            Process fileopener = new Process();
            fileopener.StartInfo.FileName = "explorer";
            fileopener.StartInfo.Arguments = "\"" + path + "\"";
            fileopener.Start();
        }

        private void lstResults_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            string filepath = lstResults.SelectedItem.ToString();
            try
            {
                OpenWithDefaultProgram(filepath);
            } catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
...