Visualizzazione dei risultati da 1 a 9 su 9
  1. #1

    [C# ...] file & directory

    Come posso creare un funzione che mi stampi in un file di testo i nomi di tutte le sottocartelle e dei file presenti in una cartella?

    sono già riuscito a creare un piccolo script in vbs che mi stampa solo i nomi di tutti i file in una cartella, ma non sò proprio come fare per i nomi delle directory...

    PS: sono alle prime armi con i linguaggi della MS.


  2. #2
    Praticamente mi servirebbe qualcosa del genere però che mi restituisse anche i nomi delle directory...
    codice:
    Dim fso 	' il file system object 
    Dim folder 	' la cartella (directory) 
    Dim file 	' il singolo file 
    Dim string 	' per contenere l'elenco 
    
    ' N.B. 	assumo che 'dirName' contenga il nome della 
    ' 	directory che si vuole 'listare' 
    
    ' creo il FSO ed accedo alla singola cartella 
    Set fso = CreateObject("Scripting.FileSystemObject") 
    Set folder = fso.GetFolder( "C:\Programmi" ) 
    
    ' pulisco la stringa 
    string = "" 
    Fol = ""
    
    ' ciclo su tutti i file della cartella 
    For Each file in folder.Files 
    string = string & file.name 
    string = string & vbCrLf 
    Next 
    
    ' a questo punto 'string' contiene l'elenco separato 
    ' da 'ritorni a capo'. 
    
    ' NOTA:
    ' si suppone che 'fileName' contenga il nome del
    ' file da scrivere.
    
    ' creo il FileSystemObject
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    ' pulisco la stringa
    'string = ""
       
    ' verifico che il file NON esista
    If Not fso.FileExists( "doc.txt" ) Then
    
       ' accedo al file
       Set file = fso.OpenTextFile( "doc.txt", 2, True, 0)
       
       ' inserisco 3 righe nel file
       file.Write String & vbCrLf
       file.Write folder & vbCrLf
    
       
       file.Close
       Set file=Nothing
       
    End If
    Set folder=Nothing 
    Set fso=Nothing
    [OT] mi scuso con i moderatori per l'errato inserimento

  3. #3
    all'interno del namespace System.IO sono presenti degli oggetti per fare anche queste cose, nello specifico usando l'oggetto

    Directory

    Si possono ottenere gli elenchi di file e directory ad un dato indirizzo

    Directory.GetFiles(@"C:\path\to\files");

    o

    Directory.GetDirectories(@"C:\path\to\directories" );

    Entrambi restituiscono un'array di string quindi ti basta fare un semplice foreach o anche un for e ti cicli i dati

    codice:
    foreach(string directoryPath in Directory.GetDirectories(@"C:\path\to\directories"))
    {
      MessageBox.Show(directoryPath);
    }
    i due metodi non ti restituiscono solo il nome dei file/directory ma il percorso completo a questi, quindi se ti serve acquisire solo il nome della directory, piuttosto che tutto il percorso, puoi benissimo usare il metodo

    GetFileName

    dell'oggetto

    Path

    Lo so, il nome dice "Acquisci il nome del file" ... xo in realtà lui va a estrarre tutto ciò che c'è tra la slash finale e la fine della stringa, di conseguenza lo si usa sul nome di una directory si ottiene il nome della directory senza il percorso

    ciau

  4. #4
    codice:
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.IO;
    
    namespace RecursiveSearchCS
    {
        /// <summary>
        /// Summary description for Form1
        /// </summary>
        public class Form1 : System.Windows.Forms.Form
        {
            internal System.Windows.Forms.Button btnSearch;
            internal System.Windows.Forms.TextBox txtFile;
            internal System.Windows.Forms.Label lblFile;
            internal System.Windows.Forms.Label lblDirectory;
            internal System.Windows.Forms.ListBox lstFilesFound;
            internal System.Windows.Forms.ComboBox cboDirectory;
            /// <summary>
            /// Required designer variable
            /// </summary>
            private System.ComponentModel.Container components = null;
    
            public Form1()
            {
                //
                // Required for Windows Form Designer support
                //
                InitializeComponent();
    
                //
                // TODO: Add any constructor code after InitializeComponent call.
                //
            }
    
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                if( disposing )
                {
                    if (components != null)
                    {
                        components.Dispose();
                    }
                }
                base.Dispose( disposing );
            }
    
            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support: do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                this.btnSearch = new System.Windows.Forms.Button();
                this.txtFile = new System.Windows.Forms.TextBox();
                this.lblFile = new System.Windows.Forms.Label();
                this.lblDirectory = new System.Windows.Forms.Label();
                this.lstFilesFound = new System.Windows.Forms.ListBox();
                this.cboDirectory = new System.Windows.Forms.ComboBox();
                this.SuspendLayout();
                //
                // btnSearch
                //
                this.btnSearch.Location = new System.Drawing.Point(608, 248);
                this.btnSearch.Name = "btnSearch";
                this.btnSearch.TabIndex = 0;
                this.btnSearch.Text = "Search";
                this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
                //
                // txtFile
                //
                this.txtFile.Location = new System.Drawing.Point(8, 40);
                this.txtFile.Name = "txtFile";
                this.txtFile.Size = new System.Drawing.Size(120, 20);
                this.txtFile.TabIndex = 4;
                this.txtFile.Text = "*.dll";
                //
                // lblFile
                //
                this.lblFile.Location = new System.Drawing.Point(8, 16);
                this.lblFile.Name = "lblFile";
                this.lblFile.Size = new System.Drawing.Size(144, 16);
                this.lblFile.TabIndex = 5;
                this.lblFile.Text = "Search for files containing:";
                //
                // lblDirectory
                //
                this.lblDirectory.Location = new System.Drawing.Point(8, 96);
                this.lblDirectory.Name = "lblDirectory";
                this.lblDirectory.Size = new System.Drawing.Size(120, 23);
                this.lblDirectory.TabIndex = 3;
                this.lblDirectory.Text = "Look In:";
                //
                // lstFilesFound
                //
                this.lstFilesFound.Location = new System.Drawing.Point(152, 8);
                this.lstFilesFound.Name = "lstFilesFound";
                this.lstFilesFound.Size = new System.Drawing.Size(528, 225);
                this.lstFilesFound.TabIndex = 1;
                //
                // cboDirectory
                //
                this.cboDirectory.DropDownWidth = 112;
                this.cboDirectory.Location = new System.Drawing.Point(8, 128);
                this.cboDirectory.Name = "cboDirectory";
                this.cboDirectory.Size = new System.Drawing.Size(120, 21);
                this.cboDirectory.TabIndex = 2;
                this.cboDirectory.Text = "ComboBox1";
                //
                // Form1
                //
                this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                this.ClientSize = new System.Drawing.Size(688, 277);
                this.Controls.AddRange(new System.Windows.Forms.Control[] {
    
                this.btnSearch,
                this.txtFile,
                this.lblFile,
                this.lblDirectory,
                this.lstFilesFound,
                this.cboDirectory});
    
                this.Name = "Form1";
                this.Text = "Form1";
                this.Load += new System.EventHandler(this.Form1_Load);
                this.ResumeLayout(false);
    
            }
            #endregion
    
            /// <summary>
            /// The main entry point for the application
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.Run(new Form1());
            }
    
            private void btnSearch_Click(object sender, System.EventArgs e)
            {
                lstFilesFound.Items.Clear();
                txtFile.Enabled = false;
                cboDirectory.Enabled = false;
                btnSearch.Text = "Searching...";
                this.Cursor = Cursors.WaitCursor;
                Application.DoEvents();
                DirSearch(cboDirectory.Text);
                btnSearch.Text = "Search";
                this.Cursor = Cursors.Default;
                txtFile.Enabled = true;
                cboDirectory.Enabled = true;
            }
    
            private void Form1_Load(object sender, System.EventArgs e)
            {
                cboDirectory.Items.Clear();
                foreach (string s in Directory.GetLogicalDrives())
                {
                    cboDirectory.Items.Add(s);
                }
                cboDirectory.Text = "C:\\";
            }
    
            void DirSearch(string sDir)
            {
                try
                {
                    foreach (string d in Directory.GetDirectories(sDir))
                    {
                        foreach (string f in Directory.GetFiles(d, txtFile.Text))
                        {
                            lstFilesFound.Items.Add(f);
                        }
                        DirSearch(d);
                      }
                }
                catch (System.Exception excpt)
                {
                    Console.WriteLine(excpt.Message);
                }
            }
        }
    }
    grazie daniele_dll ma il pezzo di codice che mi hai dato ottengo l'indirizzo assoluto di tutte le sottocartelle(e delle sottosottocartelle!) e dei file(anche quelli contenuti), insomma di tutto quello che c'è nella dir.

    A me servirebbe soltanto i nomi delle prime sottocartelle e dei file(non inclusi in nessun sottocartella): come posso usare GetFileName?

  5. #5
    beh ... il codice che ti ho dato io faceva esattamente ciò che ti serviva

    il codice che hai copiato ed incollato nel tuo progetto ti stampa a video tutte le directory usando un sistema ricorsivo


    codice:
    foreach (string directoryPath in Directory.GetDirectories(sDir))
    {
      lstFilesFound.Items.Add(directoryPath);
    }
    foreach (string filePathin Directory.GetFiles(sDir, txtFile.Text))
    {
      lstFilesFound.Items.Add(filePath);
    }
    con questo codice fai quello che ti serve

  6. #6
    quel codice l'avevo preso da msdn ...
    nn ci capisco molto di linguaggi della microsoft ma a volte sono indispensabili !!!

    Grazie daniele_dll !!!
    mitico !!!




  7. #7
    Il codice completo...
    codice:
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.IO;
    
    namespace RecursiveSearchCS
    {
        /// <summary>
        /// Summary description for Form1
        /// </summary>
        public class Form1 : System.Windows.Forms.Form
        {
            internal System.Windows.Forms.Button btnSearch;
            internal System.Windows.Forms.TextBox txtFile;
            internal System.Windows.Forms.Label lblFile;
            internal System.Windows.Forms.Label lblDirectory;
            internal System.Windows.Forms.ListBox lstFilesFound;
            internal System.Windows.Forms.ComboBox cboDirectory;
            /// <summary>
            /// Required designer variable
            /// </summary>
            private System.ComponentModel.Container components = null;
    
            public Form1()
            {
                //
                // Required for Windows Form Designer support
                //
                InitializeComponent();
    
                //
                // TODO: Add any constructor code after InitializeComponent call.
                //
            }
    
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                if( disposing )
                {
                    if (components != null)
                    {
                        components.Dispose();
                    }
                }
                base.Dispose( disposing );
            }
    
            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support: do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                this.btnSearch = new System.Windows.Forms.Button();
                this.txtFile = new System.Windows.Forms.TextBox();
                this.lblFile = new System.Windows.Forms.Label();
                this.lblDirectory = new System.Windows.Forms.Label();
                this.lstFilesFound = new System.Windows.Forms.ListBox();
                this.cboDirectory = new System.Windows.Forms.ComboBox();
                this.SuspendLayout();
                //
                // btnSearch
                //
                this.btnSearch.Location = new System.Drawing.Point(608, 248);
                this.btnSearch.Name = "btnSearch";
                this.btnSearch.TabIndex = 0;
                this.btnSearch.Text = "Search";
                this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
                //
                // txtFile
                //
                this.txtFile.Location = new System.Drawing.Point(8, 40);
                this.txtFile.Name = "txtFile";
                this.txtFile.Size = new System.Drawing.Size(120, 20);
                this.txtFile.TabIndex = 4;
                this.txtFile.Text = "*.dll";
                //
                // lblFile
                //
                this.lblFile.Location = new System.Drawing.Point(8, 16);
                this.lblFile.Name = "lblFile";
                this.lblFile.Size = new System.Drawing.Size(144, 16);
                this.lblFile.TabIndex = 5;
                this.lblFile.Text = "Search for files containing:";
                //
                // lblDirectory
                //
                this.lblDirectory.Location = new System.Drawing.Point(8, 96);
                this.lblDirectory.Name = "lblDirectory";
                this.lblDirectory.Size = new System.Drawing.Size(120, 23);
                this.lblDirectory.TabIndex = 3;
                this.lblDirectory.Text = "Look In:";
                //
                // lstFilesFound
                //
                this.lstFilesFound.Location = new System.Drawing.Point(152, 8);
                this.lstFilesFound.Name = "lstFilesFound";
                this.lstFilesFound.Size = new System.Drawing.Size(528, 225);
                this.lstFilesFound.TabIndex = 1;
                //
                // cboDirectory
                //
                this.cboDirectory.DropDownWidth = 112;
                this.cboDirectory.Location = new System.Drawing.Point(8, 128);
                this.cboDirectory.Name = "cboDirectory";
                this.cboDirectory.Size = new System.Drawing.Size(120, 21);
                this.cboDirectory.TabIndex = 2;
                this.cboDirectory.Text = "ComboBox1";
                //
                // Form1
                //
                this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                this.ClientSize = new System.Drawing.Size(688, 277);
                this.Controls.AddRange(new System.Windows.Forms.Control[] {
    
                this.btnSearch,
                this.txtFile,
                this.lblFile,
                this.lblDirectory,
                this.lstFilesFound,
                this.cboDirectory});
    
                this.Name = "Form1";
                this.Text = "Form1";
                this.Load += new System.EventHandler(this.Form1_Load);
                this.ResumeLayout(false);
    
            }
            #endregion
    
            /// <summary>
            /// The main entry point for the application
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.Run(new Form1());
            }
    
            private void btnSearch_Click(object sender, System.EventArgs e)
            {
                lstFilesFound.Items.Clear();
                txtFile.Enabled = false;
                cboDirectory.Enabled = false;
                btnSearch.Text = "Searching...";
                this.Cursor = Cursors.WaitCursor;
                Application.DoEvents();
                DirSearch(cboDirectory.Text);
                btnSearch.Text = "Search";
                this.Cursor = Cursors.Default;
                txtFile.Enabled = true;
                cboDirectory.Enabled = true;
            }
    
            private void Form1_Load(object sender, System.EventArgs e)
            {
                cboDirectory.Items.Clear();
                foreach (string s in Directory.GetLogicalDrives())
                {
                    cboDirectory.Items.Add(s);
                }
                cboDirectory.Text = "C:\\";
            }
    
            void DirSearch(string sDir)
            {
    		
    	if (System.IO.File.Exists("file.txt"))
            {
                MessageBox.Show("Il file file.txt già esiste");
            }
    
    	StreamWriter sw = new StreamWriter("file.txt");
            
                try
                {
                    foreach (string d in Directory.GetDirectories(sDir))
    		{
      		lstFilesFound.Items.Add(d);
    		sw.WriteLine(d);
    		}
    		
    		foreach (string f in Directory.GetFiles(sDir, txtFile.Text))
    		{
      		lstFilesFound.Items.Add(f);
    		sw.WriteLine(f);
    		}
    		sw.Close();	
    			
    		}
                   catch (System.Exception excpt)
                {
                    Console.WriteLine(excpt.Message);
    
                }
            }
        }
    }
    se la cartella si chiama "dir"
    nel file mi viene stampato "C:\dir"
    come faccio a far stampare solo "dir" senza il percorso( C:\ )?


  8. #8
    come ti ho detto devi usare

    Path.GetFileName

    vuole in entrata un parametro, che è la path, ovvero una string, ed in uscita da una string, che è il nome del file o della directory

  9. #9
    ok risolto !!!
    codice:
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.IO;
    
    namespace RecursiveSearchCS
    {
        /// <summary>
        /// Summary description for Form1
        /// </summary>
        public class Form1 : System.Windows.Forms.Form
        {
            internal System.Windows.Forms.Button btnSearch;
            internal System.Windows.Forms.TextBox txtFile;
            internal System.Windows.Forms.Label lblFile;
            internal System.Windows.Forms.Label lblDirectory;
            internal System.Windows.Forms.ListBox lstFilesFound;
            internal System.Windows.Forms.ComboBox cboDirectory;
            /// <summary>
            /// Required designer variable
            /// </summary>
            private System.ComponentModel.Container components = null;
    
            public Form1()
            {
                //
                // Required for Windows Form Designer support
                //
                InitializeComponent();
    
                //
                // TODO: Add any constructor code after InitializeComponent call.
                //
            }
    
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                if( disposing )
                {
                    if (components != null)
                    {
                        components.Dispose();
                    }
                }
                base.Dispose( disposing );
            }
    
            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support: do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                this.btnSearch = new System.Windows.Forms.Button();
                this.txtFile = new System.Windows.Forms.TextBox();
                this.lblFile = new System.Windows.Forms.Label();
                this.lblDirectory = new System.Windows.Forms.Label();
                this.lstFilesFound = new System.Windows.Forms.ListBox();
                this.cboDirectory = new System.Windows.Forms.ComboBox();
                this.SuspendLayout();
                //
                // btnSearch
                //
                this.btnSearch.Location = new System.Drawing.Point(608, 248);
                this.btnSearch.Name = "btnSearch";
                this.btnSearch.TabIndex = 0;
                this.btnSearch.Text = "Search";
                this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
                //
                // txtFile
                //
                this.txtFile.Location = new System.Drawing.Point(8, 40);
                this.txtFile.Name = "txtFile";
                this.txtFile.Size = new System.Drawing.Size(120, 20);
                this.txtFile.TabIndex = 4;
                this.txtFile.Text = "*.dll";
                //
                // lblFile
                //
                this.lblFile.Location = new System.Drawing.Point(8, 16);
                this.lblFile.Name = "lblFile";
                this.lblFile.Size = new System.Drawing.Size(144, 16);
                this.lblFile.TabIndex = 5;
                this.lblFile.Text = "Search for files containing:";
                //
                // lblDirectory
                //
                this.lblDirectory.Location = new System.Drawing.Point(8, 96);
                this.lblDirectory.Name = "lblDirectory";
                this.lblDirectory.Size = new System.Drawing.Size(120, 23);
                this.lblDirectory.TabIndex = 3;
                this.lblDirectory.Text = "Look In:";
                //
                // lstFilesFound
                //
                this.lstFilesFound.Location = new System.Drawing.Point(152, 8);
                this.lstFilesFound.Name = "lstFilesFound";
                this.lstFilesFound.Size = new System.Drawing.Size(528, 225);
                this.lstFilesFound.TabIndex = 1;
                //
                // cboDirectory
                //
                this.cboDirectory.DropDownWidth = 112;
                this.cboDirectory.Location = new System.Drawing.Point(8, 128);
                this.cboDirectory.Name = "cboDirectory";
                this.cboDirectory.Size = new System.Drawing.Size(120, 21);
                this.cboDirectory.TabIndex = 2;
                this.cboDirectory.Text = "ComboBox1";
                //
                // Form1
                //
                this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                this.ClientSize = new System.Drawing.Size(688, 277);
                this.Controls.AddRange(new System.Windows.Forms.Control[] {
    
                this.btnSearch,
                this.txtFile,
                this.lblFile,
                this.lblDirectory,
                this.lstFilesFound,
                this.cboDirectory});
    
                this.Name = "Form1";
                this.Text = "Form1";
                this.Load += new System.EventHandler(this.Form1_Load);
                this.ResumeLayout(false);
    
            }
            #endregion
    
            /// <summary>
            /// The main entry point for the application
            /// </summary>
            [STAThread]
            static void Main()
            {
                Application.Run(new Form1());
            }
    
            private void btnSearch_Click(object sender, System.EventArgs e)
            {
                lstFilesFound.Items.Clear();
                txtFile.Enabled = false;
                cboDirectory.Enabled = false;
                btnSearch.Text = "Searching...";
                this.Cursor = Cursors.WaitCursor;
                Application.DoEvents();
                DirSearch(cboDirectory.Text);
                btnSearch.Text = "Search";
                this.Cursor = Cursors.Default;
                txtFile.Enabled = true;
                cboDirectory.Enabled = true;
            }
    
            private void Form1_Load(object sender, System.EventArgs e)
            {
                cboDirectory.Items.Clear();
                foreach (string s in Directory.GetLogicalDrives())
                {
                    cboDirectory.Items.Add(s);
                }
                cboDirectory.Text = "C:\\";
            }
    
            void DirSearch(string sDir)
            {
    		
    	if (System.IO.File.Exists("file.txt"))
            {
            	MessageBox.Show("Il file file.txt già esiste");
    		return;
            }
    
    	StreamWriter sw = new StreamWriter("Content.txt");
            
                try
                {
                    foreach (string d in Directory.GetDirectories(sDir))
    		{
      		lstFilesFound.Items.Add(d);
    		sw.WriteLine(Path.GetFileName(d));
    		
    		}
    		
    		foreach (string f in Directory.GetFiles(sDir, txtFile.Text))
    		{
      		lstFilesFound.Items.Add(f);
    		sw.WriteLine(Path.GetFileName(f));
    		}
    		sw.Close();	
    			
    		}
                   catch (System.Exception excpt)
                {
                    Console.WriteLine(excpt.Message);
    
                }
            }
        }
    }
    grazie ancora
    spero di essere utile alla prox


Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.