Eseguire operazioni di I/O di file di base in Visual C++

Questo articolo descrive come eseguire operazioni di input/output (I/O) di file di base in Microsoft Visual C++ o in Visual C++ .NET.

Versione originale del prodotto: Visual C++
Numero KB originale: 307398

Riepilogo

Se non si ha familiarità con .NET Framework, si noterà che il modello a oggetti per le operazioni sui file in .NET Framework è simile a quello comune a FileSystemObject molti sviluppatori di Visual Studio.

Questo articolo fa riferimento agli spazi dei nomi della libreria di classi .NET Framework seguenti:

  • System::ComponentModel
  • System::Windows::Forms
  • System::Drawing

È comunque possibile usare in FileSystemObject .NET Framework. FileSystemObject Poiché è un componente COM (Component Object Model), .NET Framework richiede che l'accesso all'oggetto sia tramite il livello interoperabilità. .NET Framework genera automaticamente un wrapper per il componente se si vuole usarlo. Tuttavia, la File classe, la FileInfo classe , , DirectoryDirectoryInfo le classi e altre classi correlate in .NET Framework offrono funzionalità non disponibili con FileSystemObject, senza il sovraccarico del livello Interop.

Operazioni di I/O di file illustrate

Gli esempi in questo articolo descrivono le operazioni di I/O dei file di base. La sezione di esempio dettagliata descrive come creare un programma di esempio che illustra le sei operazioni di I/O di file seguenti:

Leggere un file di testo

Il codice di esempio seguente usa una StreamReader classe per leggere un file di testo. Il contenuto del file viene aggiunto a un controllo ListBox. Il try...catch blocco viene usato per avvisare il programma se il file è vuoto. Esistono molti modi per determinare quando viene raggiunta la fine del file; questo esempio usa il Peek metodo per esaminare la riga successiva prima di leggerla.

listBox1->Items->Clear();
try
{
    String* textFile = String::Concat(windir, (S"\\mytest.txt"));
    StreamReader *reader=new  StreamReader(textFile);
    do
    {
        listBox1->Items->Add(reader->ReadLine());
    } while(reader->Peek() != -1);
}

catch (System::Exception *e)
{
    listBox1->Items->Add(e);
}

In Visual C++ è necessario aggiungere l'opzione del compilatore di supporto di Common Language Runtime (/clr:oldSyntax) per compilare correttamente l'esempio di codice precedente come C++gestito. Per aggiungere l'opzione del compilatore di supporto di Common Language Runtime, seguire questa procedura:

  1. Fare clic su Progetto e quindi su <Proprietà NomeProgetto>.

    Nota

    <ProjectName> è un segnaposto per il nome del progetto.

  2. Espandere Proprietà di configurazione e quindi fare clic su Generale.

  3. Nel riquadro destro fare clic per selezionare Supporto di Common Language Runtime, Sintassi precedente (/clr:oldSyntax) nelle impostazioni del progetto di supporto di Common Language Runtime.

  4. Fare clic su Applica e quindi su OK.

Scrivere un file di testo

Questo codice di esempio usa una StreamWriter classe per creare e scrivere in un file. Se si dispone di un file esistente, è possibile aprirlo nello stesso modo.

StreamWriter* pwriter = new StreamWriter(S"c:\\KBTest.txt");
pwriter->WriteLine(S"File created using StreamWriter class.");
pwriter->Close();
listBox1->Items->Clear();
String *filew = new String(S"File Written to C:\\KBTest.txt");
listBox1->Items->Add(filew);

Visualizzare le informazioni sui file

Questo codice di esempio usa una FileInfo classe per accedere alle proprietà di un file. Notepad.exe viene usato in questo esempio. Le proprietà vengono visualizzate in un controllo ListBox.

listBox1->Items->Clear();
String* testfile = String::Concat(windir, (S"\\notepad.exe"));
FileInfo *pFileProps =new FileInfo(testfile);

listBox1->Items->Add(String::Concat(S"File Name = ", (pFileProps->get_FullName())));
listBox1->Items->Add(String::Concat(S"Creation Time = ", (pFileProps->get_CreationTime()).ToString()));
listBox1->Items->Add(String::Concat(S"Last Access Time = " ,(pFileProps->get_LastAccessTime()).ToString()));
listBox1->Items->Add(String::Concat(S"Last Write Time = ", (pFileProps->get_LastWriteTime()).ToString()));
listBox1->Items->Add(String::Concat(S"Size = ", (pFileProps->get_Length()).ToString()));

Elencare le unità disco

Questo codice di esempio usa le Directory classi e Drive per elencare le unità logiche in un sistema. Per questo esempio, i risultati vengono visualizzati in un controllo ListBox.

listBox1->Items->Clear();
String* drives[] = Directory::GetLogicalDrives();
int numDrives = drives->get_Length();
for (int i=0; i<numDrives; i++)
{
    listBox1->Items->Add(drives[i]);
}

Elencare le sottocartelle

Questo codice di esempio usa il GetDirectories metodo della Directory classe per ottenere un elenco di cartelle.

listBox1->Items->Clear();
String* dirs[] = Directory::GetDirectories(windir);
int numDirs = dirs->get_Length();
for (int i=0; i<numDirs; i++)
{
    listBox1->Items->Add(dirs[i]);
}

Elencare i file

Questo codice di esempio usa il GetFiles metodo della Directory classe per ottenere un elenco di file.

listBox1->Items->Clear();
String* files[]= Directory::GetFiles(this->windir);
int numFiles = files->get_Length();
for (int i=0; i<numFiles; i++)
{
    listBox1->Items->Add(files[i]);
}

Molte cose possono andare male quando un utente ottiene l'accesso ai file. I file potrebbero non esistere, i file potrebbero essere in uso o gli utenti potrebbero non avere diritti sui file delle cartelle a cui stanno tentando di accedere. Considerare queste possibilità quando si scrive codice per gestire le eccezioni che possono essere generate.

Esempio dettagliato

  1. Avviare Visual Studio .NET.

  2. Scegliere Nuovo dal menu File, quindi fare clic su Progetto.

  3. In Tipi di progetto fare clic su Progetti Visual C++. Nella sezione Modelli fare clic su Windows Forms'applicazione (.NET).

  4. Digitare KB307398 nella casella Nome , digitare C:\ nella casella Percorso e quindi fare clic su OK.

  5. Aprire la maschera Form1 nella visualizzazione Struttura e quindi premere F4 per aprire la finestra Proprietà .

  6. Nella finestra Proprietà espandere la cartella Dimensioni . Nella casella Larghezza digitare 700. Nella casella Altezza digitare 320.

  7. Aggiungere un controllo ListBox e sei controlli Button a Form1.

    Nota

    Per visualizzare la casella degli strumenti, fare clic su Casella degli strumenti dal menu Visualizza .

  8. Nella finestra Proprietà modificare le proprietà Location, Name, Size, TabIndex e Text di questi controlli come indicato di seguito:

    ID controllo Posizione Nome Dimensioni Tabindex Testo
    button1 500, 32 button1 112, 23 1 Leggi file di testo
    button2 500, 64 button2 112, 23 2 Scrivere un file di testo
    button3 500, 96 button3 112, 23 3 Visualizzare le informazioni sui file
    button4 500, 128 button4 112, 23 4 Elencare le unità
    button5 500, 160 button5 112, 23 5 Elenca sottocartelle
    button6 500, 192 button6 112, 23 6 Elencare i file
    listBox1 24, 24 listBox1 450, 200 0 listBox1
  9. Aprire il file Form1.h . Nella dichiarazione di Form1 classe dichiarare una variabile privata String con il codice seguente:

    private:
    String *windir;
    
  10. Nel costruttore della Form1 classe aggiungere il codice seguente:

    windir = System::Environment::GetEnvironmentVariable("windir");
    
  11. Per eseguire operazioni di output di input del file, aggiungere lo spazio dei System::IO nomi .

  12. Premere MAIUSC+F7 per aprire Form1 in visualizzazione Struttura. Fare doppio clic sul pulsante Leggi file di testo e quindi incollare il codice seguente:

    // How to read a text file:
    // Use try...catch to deal with a 0 byte file or a non-existant file.
    listBox1->Items->Clear();
    
    try
    {
        String* textFile = String::Concat(windir, (S"\\mytest.txt"));
        StreamReader *reader=new  StreamReader(textFile);
        do
        {
            listBox1->Items->Add(reader->ReadLine());
        } while(reader->Peek() != -1);
    }
    catch(FileNotFoundException *ex)
    {
        listBox1->Items->Add(ex);
    }  
    
    catch (System::Exception *e)
    {
        listBox1->Items->Add(e);
    }
    
  13. Nella visualizzazione Struttura form1 fare doppio clic sul pulsante Scrivi file di testo e quindi incollare il codice seguente:

    // This demonstrates how to create and to write to a text file.
    StreamWriter* pwriter = new StreamWriter(S"c:\\KBTest.txt");
    pwriter->WriteLine(S"The file was created by using the StreamWriter class.");
    pwriter->Close();
    listBox1->Items->Clear();
    String *filew = new String(S"File written to C:\\KBTest.txt");
    listBox1->Items->Add(filew);
    
  14. Nella visualizzazione Struttura form1 fare doppio clic sul pulsante Visualizza informazioni file e quindi incollare il codice seguente nel metodo :

    // This code retrieves file properties. The example uses Notepad.exe.
    listBox1->Items->Clear();
    String* testfile = String::Concat(windir, (S"\\notepad.exe"));
    FileInfo *pFileProps =new FileInfo(testfile);
    
    listBox1->Items->Add(String::Concat(S"File Name = ", (pFileProps->get_FullName())));
    listBox1->Items->Add(String::Concat(S"Creation Time = ", (pFileProps->get_CreationTime()).ToString()));
    listBox1->Items->Add(String::Concat(S"Last Access Time = " ,(pFileProps->get_LastAccessTime()).ToString()));
    listBox1->Items->Add(String::Concat(S"Last Write Time = ", (pFileProps->get_LastWriteTime()).ToString()));
    listBox1->Items->Add(String::Concat(S"Size = ", (pFileProps->get_Length()).ToString()));
    
  15. Nella visualizzazione Struttura form1 fare doppio clic sul pulsante Elenca unità e quindi incollare il codice seguente:

    // This demonstrates how to obtain a list of disk drives.
    listBox1->Items->Clear();
    String* drives[] = Directory::GetLogicalDrives();
    int numDrives = drives->get_Length();
    for (int i=0; i<numDrives; i++)
    {
        listBox1->Items->Add(drives[i]);
    }
    
  16. Nella visualizzazione Struttura form1 fare doppio clic sul pulsante Elenca sottocartelle e quindi incollare il codice seguente:

    // This code obtains a list of folders. This example uses the Windows folder.
    listBox1->Items->Clear();
    String* dirs[] = Directory::GetDirectories(windir);
    int numDirs = dirs->get_Length();
    for (int i=0; i<numDirs; i++)
    {
        listBox1->Items->Add(dirs[i]);
    }
    
  17. Nella visualizzazione Struttura di Form1 fare doppio clic sul pulsante Elenca file e quindi incollare il codice seguente:

    // This code obtains a list of files. This example uses the Windows folder.
    listBox1->Items->Clear();
    String* files[]= Directory::GetFiles(this->windir);
    int numFiles = files->get_Length();
    for (int i=0; i<numFiles; i++)
    {
        listBox1->Items->Add(files[i]);
    }
    
  18. Per compilare ed eseguire il programma, premere CTRL+F5.

Esempio di codice completo

//Form1.h
#pragma once

namespace KB307398
{
    using namespace System;
    using namespace System::IO;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;

    /// <summary>
    /// Summary for Form1
    /// WARNING: If you change the name of this class, you will need to change the
    ///          'Resource File Name' property for the managed resource compiler tool
    ///          associated with all .resx files this class depends on.  Otherwise,
    ///          the designers will not be able to interact properly with localized
    ///          resources associated with this form.
    /// </summary>
    public __gc class Form1 : public System::Windows::Forms::Form
    {
        private:
        String *windir;
        public:
        Form1(void)
        {
            windir = System::Environment::GetEnvironmentVariable("windir");
            InitializeComponent();
        }

        protected:
        void Dispose(Boolean disposing)
        {
            if (disposing && components)
            {
            components->Dispose();
            }
            __super::Dispose(disposing);
        }
        private: System::Windows::Forms::Button *  button1;
        private: System::Windows::Forms::Button *  button2;
        private: System::Windows::Forms::Button *  button3;
        private: System::Windows::Forms::Button *  button4;
        private: System::Windows::Forms::Button *  button5;
        private: System::Windows::Forms::Button *  button6;
        private: System::Windows::Forms::ListBox *  listBox1;

        private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
        System::ComponentModel::Container * components;

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            this->button1 = new System::Windows::Forms::Button();
            this->button2 = new System::Windows::Forms::Button();
            this->button3 = new System::Windows::Forms::Button();
            this->button4 = new System::Windows::Forms::Button();
            this->button5 = new System::Windows::Forms::Button();
            this->button6 = new System::Windows::Forms::Button();
            this->listBox1 = new System::Windows::Forms::ListBox();
            this->SuspendLayout();
            // button1
            this->button1->Location = System::Drawing::Point(500, 32);
            this->button1->Name = S"button1";
            this->button1->Size = System::Drawing::Size(112, 23);
            this->button1->TabIndex = 1;
            this->button1->Text = S"Read Text File";
            this->button1->Click += new System::EventHandler(this, button1_Click);
            // button2
            this->button2->Location = System::Drawing::Point(500, 64);
            this->button2->Name = S"button2";
            this->button2->Size = System::Drawing::Size(112, 23);
            this->button2->TabIndex = 2;
            this->button2->Text = S"Write Text File";
            this->button2->Click += new System::EventHandler(this, button2_Click);
            // button3
            this->button3->Location = System::Drawing::Point(500, 96);
            this->button3->Name = S"button3";
            this->button3->Size = System::Drawing::Size(112, 23);
            this->button3->TabIndex = 3;
            this->button3->Text = S"View File Information";
            this->button3->Click += new System::EventHandler(this, button3_Click);
            // button4
            this->button4->Location = System::Drawing::Point(500, 128);
            this->button4->Name = S"button4";
            this->button4->Size = System::Drawing::Size(112, 23);
            this->button4->TabIndex = 4;
            this->button4->Text = S"List Drives";
            this->button4->Click += new System::EventHandler(this, button4_Click);
            // button5
            this->button5->Location = System::Drawing::Point(500, 160);
            this->button5->Name = S"button5";
            this->button5->Size = System::Drawing::Size(112, 23);
            this->button5->TabIndex = 5;
            this->button5->Text = S"List Subfolders";
            this->button5->Click += new System::EventHandler(this, button5_Click);
            // button6
            this->button6->Location = System::Drawing::Point(500, 188);
            this->button6->Name = S"button6";
            this->button6->Size = System::Drawing::Size(112, 23);
            this->button6->TabIndex = 6;
            this->button6->Text = S"List Files";
            this->button6->Click += new System::EventHandler(this, button6_Click);
            // listBox1
            this->listBox1->Location = System::Drawing::Point(24, 24);
            this->listBox1->Name = S"listBox1";
            this->listBox1->Size = System::Drawing::Size(450, 199);
            this->listBox1->TabIndex = 0;
            // Form1
            this->AutoScaleBaseSize = System::Drawing::Size(5, 13);
            this->ClientSize = System::Drawing::Size(692, 293);
            this->Controls->Add(this->listBox1);
            this->Controls->Add(this->button6);
            this->Controls->Add(this->button5);
            this->Controls->Add(this->button4);
            this->Controls->Add(this->button3);
            this->Controls->Add(this->button2);
            this->Controls->Add(this->button1);
            this->Name = S"Form1";
            this->Text = S"Form1";
            this->ResumeLayout(false);
        }
        private: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)
        {
            // This code shows how to read a text file.
            // The try...catch code is to deal with a 0 byte file or a non-existant file.
            listBox1->Items->Clear();

            try
            {
                String* textFile = String::Concat(windir, (S"\\mytest.txt"));
                StreamReader *reader=new  StreamReader(textFile);
                do
                {
                    listBox1->Items->Add(reader->ReadLine());
                }
                while(reader->Peek() != -1);
            }
            catch(FileNotFoundException *ex)
            {
                listBox1->Items->Add(ex);
            }

            catch (System::Exception *e)
            {
                listBox1->Items->Add(e);
            }
        }

        private: System::Void button2_Click(System::Object *  sender, System::EventArgs *  e)
        {
            // This code demonstrates how to create and to write to a text file.
            StreamWriter* pwriter = new StreamWriter(S"c:\\KBTest.txt");
            pwriter->WriteLine(S"The file was created by using the StreamWriter class.");
            pwriter->Close();
            listBox1->Items->Clear();
            String *filew = new String(S"The file was written to C:\\KBTest.txt");
            listBox1->Items->Add(filew);
        }

        private: System::Void button3_Click(System::Object *  sender, System::EventArgs *  e)
         {
            // This code retrieves file properties. This example uses Notepad.exe.
            listBox1->Items->Clear();
            String* testfile = String::Concat(windir, (S"\\notepad.exe"));
            FileInfo *pFileProps  =new FileInfo(testfile);

            listBox1->Items->Add(String::Concat(S"File Name = ", (pFileProps->get_FullName() )) );
            listBox1->Items->Add(String::Concat(S"Creation Time = ", (pFileProps->get_CreationTime() ).ToString()) );
            listBox1->Items->Add(String::Concat(S"Last Access Time = "  ,(pFileProps->get_LastAccessTime() ).ToString()) );
            listBox1->Items->Add(String::Concat(S"Last Write Time = ", (pFileProps->get_LastWriteTime() ).ToString()) );
            listBox1->Items->Add(String::Concat(S"Size = ", (pFileProps->get_Length() ).ToString()) );
        }

        private: System::Void button4_Click(System::Object *  sender, System::EventArgs *  e)
        {
            // The code demonstrates how to obtain a list of disk drives.
            listBox1->Items->Clear();
            String* drives[] = Directory::GetLogicalDrives();
            int numDrives = drives->get_Length();
            for (int i=0; i<numDrives; i++)
            {
                listBox1->Items->Add(drives[i]);
            }
        }

        private: System::Void button5_Click(System::Object *  sender, System::EventArgs *  e)
        {
            // This code obtains a list of folders. This example uses the Windows folder.
            listBox1->Items->Clear();
            String* dirs[] = Directory::GetDirectories(windir);
            int numDirs = dirs->get_Length();
            for (int i=0; i<numDirs; i++)
            {
                listBox1->Items->Add(dirs[i]);
            }
        }

        private: System::Void button6_Click(System::Object *  sender, System::EventArgs *  e)
        {
            // This code obtains a list of files. This example uses the Windows folder.
            listBox1->Items->Clear();
            String* files[]= Directory::GetFiles(this->windir);
            int numFiles = files->get_Length();
            for (int i=0; i<numFiles; i++)
            {
                listBox1->Items->Add(files[i]);
            }
        }
    };
}

//Form1.cpp
#include "stdafx.h"
#include "Form1.h"
#include <windows.h>

using namespace KB307398;

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
    System::Threading::Thread::CurrentThread->ApartmentState = System::Threading::ApartmentState::STA;
    Application::Run(new Form1());
    return 0;
}

Riferimenti

Per altre informazioni, visitare supporto tecnico Microsoft. Per altre informazioni su come creare Windows Form nelle estensioni gestite per C++, vedere l'esempio ManagedCWinFormWiz nella Guida di Visual Studio .NET.