Avatar billede Slettet bruger
02. januar 2006 - 16:37 Der er 11 kommentarer

Gennemsøg mappe og undermapper

Hey, jeg står her med et lidt svært problem, for mig ivertfald. Jeg skal lave en funktion der smidder alle musik filer fra en bestemt mappe ind i mit listview. Problemet er, at jeg kun kan finde ud af at lave funktionen så den finder filerne i den valgte mappe, ikke i undermapper og undermapper af dem osv osv.. altså hvor den gennemsøger hver enkelt mappe for filer.

Jeg har haft lavet det før i et andet sprog, men har detsværre mistet koden..

Håber nogen kan hjælpe mig, bare et simpelt eksempel ikke noget fansi :)

Et lille udpluk for at sætte nogen i gang evt:

private void OpenFolder(string path)
        {

            String[] dirs;
            try
            {
                dirs = Directory.GetDirectories(path);
            }
            catch (Exception)
            {
                return;
            }

            for (int i = 0; i < dirs.Length; i++)
            {
             
               
            }
        }
Avatar billede arne_v Ekspert
02. januar 2006 - 16:41 #1
Problemet plejer at blive løst ved at lade metoden kalde sig selv rekursivt !
Avatar billede Slettet bruger
02. januar 2006 - 16:45 #2
ja det er netop det, men jeg er virkelig dårlig til at sidde og regne sådan noget ud, for der skal køre to lykker, og den skal springe ud og ind ad dem osv
Avatar billede dr_chaos Nybegynder
02. januar 2006 - 16:49 #3
noget i denne stil
//for alle directories i TI_Egenkontrol dir.
            foreach (string dir in Directory.GetDirectories(path))
            {
                foreach (string file in Directory.GetFiles(dir))
                {

                   
                }
            }
Avatar billede arne_v Ekspert
02. januar 2006 - 16:51 #4
her er noget kode som finder alle .cs filer på mit C drev:

using System;
using System.IO;

class MainClass
{
    public static void lookup(String dir)
    {
        string[] files = Directory.GetFiles(dir, "*.cs");
        foreach(string f in files)
        {
            Console.WriteLine(f);
        }
        string[] dirs = Directory.GetDirectories(dir);
        foreach(string d in dirs)
        {
            lookup(d);
        }
    }
    public static void Main(string[] args)
    {
        lookup(@"C:\");
    }
}
Avatar billede innercitydk Nybegynder
02. januar 2006 - 16:53 #5
Prøv lige det her (skal tilpasses til dit program)

Metoden er lavet rekursiv, dvs at den "scanner" alle filer i den specificerede mappe og undermapper hvis du lader recursive være true.

public void backupDb(object sender, System.EventArgs e)
{
    string srcdir;
    bool  recursive;

    recursive = true;
    srcdir = "mappen du vil hente fra\\";
           
    scannerHelper(srcdir, recursive);       
}

private static void scannerHelper(string srcdir, bool recursive)
{
    DirectoryInfo  dir;
    FileInfo[]      files;
    DirectoryInfo[] dirs;
    string          tmppath;

    dir = new DirectoryInfo(srcdir);
    if (!dir.Exists)
    {
        throw new ArgumentException("Mappen eksisterer ikke -> " + srcdir);
    }
    files = dir.GetFiles();
    foreach(FileInfo file in files)
    {             
        listView1.Items.Add(file.name);
    }
    files = null;
    if (!recursive)
    {
        return;
    }
    dirs = dir.GetDirectories();
    foreach(DirectoryInfo subdir in dirs)
    {
        scannerHelper(subdir.FullName, recursive);
    }
    dirs = null;
    dir = null;
}

Vh Nicki
Avatar billede innercitydk Nybegynder
02. januar 2006 - 16:55 #6
jeg glemte at slette linien: string tmppath;
den bliver ikke brugt.. vh
Avatar billede Slettet bruger
02. januar 2006 - 16:56 #7
okay, rigtig mange tak, jeg kigger lige lidt på det, alle ser ud til at være lige det jeg skal bruge, og det var mere simpelt end jeg havde troet!
Avatar billede bitsch Nybegynder
02. januar 2006 - 19:48 #8
Da det er lidt af en tung process at fyre af, så overvej at bruge en BackgroundWorker til en asynkron process.

Her er et link til et eksempel.
http://msdn2.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
Avatar billede bitsch Nybegynder
03. januar 2006 - 00:12 #9
Følgende eksempel viser hvorledes løsningen fra "arne v" kan anvendes sammen med en BackgroundWorker:


namespace FileSearch
{
    using System;
    using System.IO;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Globalization;

    public partial class SearchDialog : Form
    {
        private BackgroundWorker backgroundWorker;

        // This delegate enables asynchronous calls for setting the result on the ListView control.
        private delegate void AddResultCallback(string text);

        // This delegate enables asynchronous calls for setting the text on the status label.
        private delegate void SetMessageCallback(string text);

        public SearchDialog()
        {
            InitializeComponent();

            this.AcceptButton = this.buttonSearch;

            this.buttonSearch.Enabled = true;
            this.buttonCancel.Enabled = false;

            #region FolderBrowserDialog

            this.folderBrowserDialog.SelectedPath = @"C:\";
            this.folderBrowserDialog.ShowNewFolderButton = false;
            this.folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer;

            #endregion // FolderBrowserDialog

            this.textBoxLookIn.Text = this.folderBrowserDialog.SelectedPath;

            this.InitializeBackgoundWorker();
        }

        #region BackgroundWorker

        /// <summary>
        // Set up the BackgroundWorker object by attaching event handlers.
        /// </summary>
        private void InitializeBackgoundWorker()
        {
            this.backgroundWorker = new BackgroundWorker();
            this.backgroundWorker.WorkerSupportsCancellation = true;

            this.backgroundWorker.DoWork += new DoWorkEventHandler(BackgroundWorkerDoWork);
            this.backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorkerRunWorkerCompleted);
        }

        private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            // Get the BackgroundWorker that raised this event.
            BackgroundWorker backgroundWorker = sender as BackgroundWorker;

            this.SetMessage("Searching...");

            // Assign the result of the computation to the Result property of the DoWorkEventArgs
            // object. This is will be available to the RunWorkerCompleted eventhandler.
            // doWorkEventArgs.Result = this.Search(backgroundWorker, doWorkEventArgs /*, Parameter (Optional)*/ );
            this.Search(backgroundWorker, doWorkEventArgs /*, Parameter (Optional)*/ );
        }

        private void BackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
        {
            // First, handle the case where an exception was thrown.
            if (runWorkerCompletedEventArgs.Error != null)
            {
                this.SetMessage("Error: " + runWorkerCompletedEventArgs.Error.Message);
            }
            else if (runWorkerCompletedEventArgs.Cancelled)
            {
                // Next, handle the case where the user canceled the operation.
                // Note that due to a race condition in the DoWork event handler, the Cancelled
                // flag may not have been set, even though CancelAsync was called.
                this.SetMessage("Canceled");
            }
            else
            {
                // Finally, handle the case where the operation succeeded.
                this.SetMessage("Search Ended");
            }

            // Enable the Start button.
            this.buttonSearch.Enabled = true;

            // Disable the Cancel button.
            this.buttonCancel.Enabled = false;
        }

        #endregion // BackgroundWorker

        private void ButtonSearchClick(object sender, EventArgs e)
        {
            this.listViewResults.Items.Clear();

            // Disable the Search button until the asynchronous operation is done.
            this.buttonSearch.Enabled = false;

            // Enable the Cancel button while the asynchronous operation runs.
            this.buttonCancel.Enabled = true;

            // Start the asynchronous operation.
            // this.backgroundWorker.RunWorkerAsync(parameter (optional));
            this.backgroundWorker.RunWorkerAsync();
        }

        private void ButtonCancelClick(object sender, EventArgs e)
        {
            this.backgroundWorker.CancelAsync();

            // Disable the Cancel button.
            this.buttonCancel.Enabled = false;
        }

        private void ButtonDirectoryClick(object sender, EventArgs e)
        {
            DialogResult dialogResult = this.folderBrowserDialog.ShowDialog();

            if (dialogResult == DialogResult.OK)
            {
                this.textBoxLookIn.Text = this.folderBrowserDialog.SelectedPath;
            }
        }

        // This is the method that does the actual work. For this
        // example, it computes a Fibonacci number and
        // reports progress as it does its work.
        private void Search(BackgroundWorker backgroundWorker, DoWorkEventArgs doWorkEventArgs /*, Parameter (Optional)*/)
        {
            this.Lookup(this.textBoxLookIn.Text, backgroundWorker, doWorkEventArgs);
        }

        private void Lookup(String directory, BackgroundWorker backgroundWorker, DoWorkEventArgs doWorkEventArgs)
        {
            if (backgroundWorker.CancellationPending)
            {
                doWorkEventArgs.Cancel = true;
                return;
            }
            else
            {
                try
                {
                    string[] files = Directory.GetFiles(directory, "*.cs");

                    foreach (string file in files)
                    {
                        this.AddResult(file);
                    }

                    string[] directories = Directory.GetDirectories(directory);

                    foreach (string d in directories)
                    {
                        this.Lookup(d, backgroundWorker, doWorkEventArgs);
                    }
                }
                catch (ArgumentException argumentException)
                {
                    MessageBox.Show(String.Format(CultureInfo.CurrentUICulture, "Unable to search.\nReason: {0}", argumentException.Message), "Search Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (UnauthorizedAccessException unauthorizedAccessException)
                {
                    this.AddResult(unauthorizedAccessException.Message);
                }
                catch (DirectoryNotFoundException directoryNotFoundException)
                {
                    this.AddResult("*** Unknown Directory: " + directoryNotFoundException.Message);
                }
            }
        }

        /// <summary>
        /// This method demonstrates a pattern for making thread-safe calls on a Windows Forms control.
        ///
        /// If the calling thread is different from the thread that
        /// created the TextBox control, this method creates a SetTextCallback and calls itself asynchronously using the
        /// Invoke method.
        ///
        /// If the calling thread is the same as the thread that created
        /// the TextBox control, the Text property is set directly.
        ///
        /// Read more on: http://msdn2.microsoft.com/en-us/library/ms171728.aspx
        /// </summary>
        /// <param name="text">Text to be added to the list.</param>
        private void AddResult(string text)
        {
            // InvokeRequired required compares the thread ID of the calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.listViewResults.InvokeRequired)
            {
                AddResultCallback setTextCallback = new AddResultCallback(AddResult);
                this.Invoke(setTextCallback, new object[] { text });
            }
            else
            {
                this.listViewResults.Items.Add(text);
            }
        }

        /// <summary>
        /// This method demonstrates a pattern for making thread-safe calls on a Windows Forms control.
        ///
        /// If the calling thread is different from the thread that
        /// created the TextBox control, this method creates a SetTextCallback and calls itself asynchronously using the
        /// Invoke method.
        ///
        /// If the calling thread is the same as the thread that created
        /// the TextBox control, the Text property is set directly.
        ///
        /// Read more on: http://msdn2.microsoft.com/en-us/library/ms171728.aspx
        /// </summary>
        /// <param name="text">Text to be added to the list.</param>
        private void SetMessage(string text)
        {
            // InvokeRequired required compares the thread ID of the calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.labelMessage.InvokeRequired)
            {
                SetMessageCallback setMessageCallback = new SetMessageCallback(SetMessage);
                this.Invoke(setMessageCallback, new object[] { text });
            }
            else
            {
                this.labelMessage.Text = text;
            }
        }
    }
}
Avatar billede bitsch Nybegynder
03. januar 2006 - 00:42 #10
Nb! Det er kun et hurtigt eksempel, så f.eks. bør man fange ObjectDisposedException i de to callback metoder (i det mindste i AddResult). Derudover bør man stoppe BackgroundWorkeren inden dialogen lukkes.
Avatar billede dr_chaos Nybegynder
04. februar 2006 - 17:09 #11
Du mangler at lukke spørgsmålet.
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
IT-kurser om Microsoft 365, sikkerhed, personlig vækst, udvikling, digital markedsføring, grafisk design, SAP og forretningsanalyse.

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester