Temel dosya G/Ç'sini yapmak için Visual C# kullanma

Bu makalede, Visual C# içinde temel dosya G/Ç'sini nasıl gerçekleştirebileceğiniz açıklanır ve bu görevin nasıl gerçekleştirileceklerini gösteren bir kod örneği sağlanır.

Orijinal ürün sürümü: Visual C#
Özgün KB numarası: 304430

Özet

Not

Bu adım adım makalede, Visual C# içinde altı temel dosya girişi/çıkışı (G/Ç) işlemi gerçekleştirme adımları gösterilmektedir. .NET Framework yeniyseniz, .NET'teki dosya işlemleri için nesne modelinin birçok Visual Studio 6.0 geliştiricisi tarafından popüler olan (FSO) ile benzer FileSystemObject olduğunu göreceksiniz. Geçişi kolaylaştırmak için, Visual Basic ile FileSystemObject'i Kullanma başlığı altında görüntülenen işlevsellik.

.NET'te kullanmaya FileSystemObject devam edebilirsiniz. FileSystemObject bir Bileşen Nesne Modeli (COM) bileşeni olduğundan, .NET nesneye erişimin Birlikte Çalışma katmanı üzerinden olmasını gerektirir. Microsoft .NET, kullanmak istiyorsanız bileşen için bir sarmalayıcı oluşturur. Ancak, File.NET Framework içindeki , DirectoryFileInfo, , sınıfları DirectoryInfo ve diğer ilgili sınıflar, Birlikte Çalışma katmanının ek yükü olmadan FSO ile kullanılamayan işlevler sunar.

Dosya G/Ç işlemleri gösterildi

Bu makaledeki örneklerde temel dosya G/Ç işlemleri açıklanmaktadır. Adım adım örnek bölümünde, aşağıdaki dosya G/Ç işlemlerini gösteren örnek bir programın nasıl oluşturulacağı açıklanır:

  • Metin dosyası okuma
  • Metin dosyası yazma
  • Dosya bilgilerini görüntüleme
  • Disk sürücülerini listeleme
  • Liste klasörleri
  • Dosyaları listeleme

Aşağıdaki kod örneklerini doğrudan kullanmak istiyorsanız aşağıdakilere dikkat edin:

  • Ad alanını System.IO aşağıdaki gibi ekleyin:

    using System.IO;
    
  • Değişkenini winDir aşağıdaki gibi bildirin:

    string winDir=System.Environment.GetEnvironmentVariable("windir");
    
  • addListItem İşlev aşağıdaki gibi bildirilir:

    private void addListItem(string value)
    {
        this.listBox1.Items.Add(value);
    }
    

    işlevini bildirmek ve kullanmak addListItem yerine aşağıdaki deyimi doğrudan kullanabilirsiniz:

    this.listBox1.Items.Add(value);
    

Metin dosyası okuma

Aşağıdaki örnek kod ,System.ini dosyasını okumak için bir StreamReader sınıf kullanır. Dosyanın içeriği listbox denetimine eklenir. Blok try...catch , dosya boşsa programı uyarmak için kullanılır. Dosyanın sonuna ulaşıldığında belirlemenin birçok yolu vardır; Bu örnek, okumadan önce sonraki satırı incelemek için yöntemini kullanır Peek .

StreamReader reader=new StreamReader(winDir + "\\system.ini");
try
{
    do
    {
        addListItem(reader.ReadLine());
    }
    while(reader.Peek()!= -1);
}
catch
{
    addListItem("File is empty");
}
finally
{
    reader.Close();
}

Metin dosyası yazma

Bu örnek kod, dosya StreamWriter oluşturmak ve dosyaya yazmak için bir sınıf kullanır. Mevcut bir dosyanız varsa, dosyayı aynı şekilde açabilirsiniz.

StreamWriter writer = new StreamWriter("c:\\KBTest.txt");
writer.WriteLine("File created using StreamWriter class.");
writer.Close();
this.listbox1.Items.Clear();
addListItem("File Written to C:\\KBTest.txt");

Dosya bilgilerini görüntüleme

Bu örnek kod, bir FileInfo dosyanın özelliklerine erişmek için bir nesne kullanır. Notepad.exe bu örnekte kullanılır. Özellikler bir ListBox denetiminde görünür.

FileInfo FileProps =new FileInfo(winDir + "\\notepad.exe");
addListItem("File Name = " + FileProps.FullName);
addListItem("Creation Time = " + FileProps.CreationTime);
addListItem("Last Access Time = " + FileProps.LastAccessTime);
addListItem("Last Write TIme = " + FileProps.LastWriteTime);
addListItem("Size = " + FileProps.Length);
FileProps = null;

Disk sürücülerini listeleme

Bu örnek kod, sistemdeki Directory mantıksal sürücüleri listelemek için ve Drive sınıflarını kullanır. Bu örnek için sonuçlar ListBox denetiminde görünür.

string[] drives = Directory.GetLogicalDrives();
foreach(string drive in drives)
{
    addListItem(drive);
}

Alt klasörleri listeleme

Bu örnek kod, klasörlerin GetDirectoriesDirectory listesini almak için sınıfının yöntemini kullanır.

string[] dirs = Directory.GetDirectories(winDir);
foreach(string dir in dirs)
{
    addListItem(dir);
}

Dosyaları listeleme

Bu örnek kod, dosyaların listesini almak için sınıfının yöntemini Directory kullanırGetFiles.

string[] files= Directory.GetFiles(winDir);
foreach (string i in files)
{
    addListItem(i);
}

Kullanıcı dosyalara eriştiğinde birçok sorun oluşabilir. Dosyalar mevcut olmayabilir, dosyalar kullanımda olabilir veya kullanıcıların erişmeye çalıştıkları dosya veya klasörler üzerinde hakları olmayabilir. Kod yazarken bu olasılıkları göz önünde bulundurmak ve oluşturulabilecek özel durumları işlemek önemlidir.

Adım adım örnek

  1. Visual C# uygulamasında yeni bir Windows Forms Uygulaması oluşturun. Varsayılan olarak Form1 oluşturulur.

  2. Form1 (Form1.cs) için kod penceresini açın.

  3. Form1.cs tüm kodu silin.

  4. Aşağıdaki kodu Arka Planda Kod Düzenleyici penceresine yapıştırın.

    using System.Windows.Forms;
    using System.IO;
    
    namespace fso_cs
    {
        public partial class Form1 : Form
        {
            string winDir = System.Environment.GetEnvironmentVariable("windir");
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, System.EventArgs e)
            {
                //How to read a text file.
                //try...catch is to deal with a 0 byte file.
                this.listBox1.Items.Clear();
                StreamReader reader = new StreamReader(winDir + "\\system.ini");
                try
                {
                    do
                    {
                        addListItem(reader.ReadLine());
                    }
                    while (reader.Peek()!= -1);
                }
                catch
                {
                    addListItem("File is empty");
                }
                finally
                {
                    reader.Close();
                }
            }
    
            private void button2_Click(object sender, System.EventArgs e)
            {
                //Demonstrates how to create and write to a text file.
                StreamWriter writer = new StreamWriter("c:\\KBTest.txt");
                writer.WriteLine("File created using StreamWriter class.");
                writer.Close();
                this.listBox1.Items.Clear();
                addListItem("File Written to C:\\KBTest.txt");
            }
    
            private void button3_Click(object sender, System.EventArgs e)
            {
                //How to retrieve file properties (example uses Notepad.exe).
                this.listBox1.Items.Clear();
                FileInfo FileProps = new FileInfo(winDir + "\\notepad.exe");
                addListItem("File Name = " + FileProps.FullName);
                addListItem("Creation Time = " + FileProps.CreationTime);
                addListItem("Last Access Time = " + FileProps.LastAccessTime);
                addListItem("Last Write TIme = " + FileProps.LastWriteTime);
                addListItem("Size = " + FileProps.Length);
                FileProps = null;
            }
    
            private void button4_Click(object sender, System.EventArgs e)
            {
                //Demonstrates how to obtain a list of disk drives.
                this.listBox1.Items.Clear();
                string[] drives = Directory.GetLogicalDrives();
                foreach (string drive in drives)
                {
                    addListItem(drive);
                }
            }
    
            private void button5_Click(object sender, System.EventArgs e)
            {
                //How to get a list of folders (example uses Windows folder). 
                this.listBox1.Items.Clear();
                string[] dirs = Directory.GetDirectories(winDir);
                foreach (string dir in dirs)
                {
                    addListItem(dir);
                }
            }
    
            private void button6_Click(object sender, System.EventArgs e)
            {
                //How to obtain list of files (example uses Windows folder).
                this.listBox1.Items.Clear();
                string[] files = Directory.GetFiles(winDir);
                foreach (string i in files)
                {
                    addListItem(i);
                }
            }
    
            private void Form1_Load(object sender, System.EventArgs e)
            {
                this.button1.Text = "Read Text File";
                this.button2.Text = "Write Text File";
                this.button3.Text = "View File Information";
                this.button4.Text = "List Drives";
                this.button5.Text = "List Subfolders";
                this.button6.Text = "List Files";
            }
    
            private void addListItem(string value)
            {
                this.listBox1.Items.Add(value);
            }
        }
    }
    
  5. Form1.Tasarım Aracı için kod penceresini açın. cs.

  6. Form1.Tasarım Aracı'daki tüm kodu silin. cs.

  7. Aşağıdaki kodu Form1.Tasarım Aracı'a yapıştırın. cs.

    namespace fso_cs
    {
        partial class Form1
        {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.IContainer components = null;
    
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (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.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 = new System.Drawing.Point(53, 30);
                this.button1.Name = "button1";
                this.button1.Size = new System.Drawing.Size(112, 23);
                this.button1.TabIndex = 1;
                this.button1.Text = "button1";
                this.button1.Click += new System.EventHandler(this.button1_Click);
    
                // button2
                this.button2.Location = new System.Drawing.Point(53, 62);
                this.button2.Name = "button2";
                this.button2.Size = new System.Drawing.Size(112, 23);
                this.button2.TabIndex = 2;
                this.button2.Text = "button2";
                this.button2.Click += new System.EventHandler(this.button2_Click);
    
                // button3
                this.button3.Location = new System.Drawing.Point(53, 94);
                this.button3.Name = "button3";
                this.button3.Size = new System.Drawing.Size(112, 23);
                this.button3.TabIndex = 3;
                this.button3.Text = "button3";
                this.button3.Click += new System.EventHandler(this.button3_Click);
    
                // button4
                this.button4.Location = new System.Drawing.Point(53, 126);
                this.button4.Name = "button4";
                this.button4.Size = new System.Drawing.Size(112, 23);
                this.button4.TabIndex = 4;
                this.button4.Text = "button4";
                this.button4.Click += new System.EventHandler(this.button4_Click);
    
                // button5
                this.button5.Location = new System.Drawing.Point(53, 158);
                this.button5.Name = "button5";
                this.button5.Size = new System.Drawing.Size(112, 23);
                this.button5.TabIndex = 5;
                this.button5.Text = "button5";
                this.button5.Click += new System.EventHandler(this.button5_Click);
    
                // button6
                this.button6.Location = new System.Drawing.Point(53, 190);
                this.button6.Name = "button6";
                this.button6.Size = new System.Drawing.Size(112, 23);
                this.button6.TabIndex = 6;
                this.button6.Text = "button6";
                this.button6.Click += new System.EventHandler(this.button6_Click);
    
                // listBox1
                this.listBox1.FormattingEnabled = true;
                this.listBox1.Location = new System.Drawing.Point(204, 30);
                this.listBox1.Name = "listBox1";
                this.listBox1.Size = new System.Drawing.Size(270, 199);
                this.listBox1.TabIndex = 7;
    
                // Form1
                this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                this.ClientSize = new System.Drawing.Size(525, 273);
                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.Controls.Add(this.listBox1);
                this.Name = "Form1";
                this.Text = "Form1";
                this.Load += new System.EventHandler(this.Form1_Load);
                this.ResumeLayout(false);
            }
            #endregion
    
            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;
        }
    }
    
  8. Varsayılan olarak, Windows Forms proje oluşturduğunuzda Visual C# projeye bir form ekler. Bu form Form1 olarak adlandırılır. Formu temsil eden iki kaynak kod dosyası Form1.cs ve Form1.Tasarım Aracı olarak adlandırılır. cs. Kodunuzu Form1.cs dosyasına yazarsınız. Windows Forms Tasarım Aracı, Tasarımcı tarafından oluşturulan kodu Form1.Tasarım Aracı yazar. cs dosyası. Yukarıdaki adımlarda yer alan kod bu kuruluşu yansıtır.

  9. Programı derlemek ve çalıştırmak için F5 tuşuna basın. Farklı eylemleri görüntülemek için düğmelere tıklayın. Örnek kodu görüntülediğinizde, bu kodu gizlemek için Windows Form Tasarım Aracı Oluşturulan Kod adlı alanı daraltmak isteyebilirsiniz.