Skip to content
The Chat Archive
gpt-4.1-mini-2025-04-14· OpenAI WildChat-4.8M (AI2)

Перепиши в оконном интерфейсе C# Forms с возможностью выбора файлов и использованием…

  1. User

    Перепиши в оконном интерфейсе C# Forms с возможностью выбора файлов и использованием стандартных диалогов данный ниже код и распиши все файлы проекта и весь код в них: " using System; using System.IO; using System.Threading; using System.Text;

    namespace AsyncReadCallBack { class AsyncReadCallBackClass { private static Byte[] staticData = new Byte[100];

    static void Main(string[] args)
    {
        //AsyncReadOneFileCallBack();
        //AsyncReadOneFileCallBackAnonimus();
        AsyncReadMultiplyFilesAnonimus();
    
    
    }
    
    private static void AsyncReadOneFileCallBack()
    {
        Console.WriteLine("Основной поток ID = {0}",
           Thread.CurrentThread.ManagedThreadId);
    
        FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open,
                                       FileAccess.Read, FileShare.Read, 1024,
                                       FileOptions.Asynchronous);
    
        fs.BeginRead(staticData, 0, staticData.Length, ReadIsComplete, fs);
        Console.ReadLine();
    }
    
    private static void ReadIsComplete(IAsyncResult ar)
    {
        Console.WriteLine("Чтение в потоке {0} закончено",
           Thread.CurrentThread.ManagedThreadId);
    
        FileStream fs = (FileStream)ar.AsyncState;
    
        Int32 bytesRead = fs.EndRead(ar);
    
        fs.Close();
    
        Console.WriteLine("Количество считаных байт = {0}", bytesRead);
        Console.WriteLine(Encoding.UTF8.GetString(staticData).Remove(0, 1));
    }
    
    private static void AsyncReadOneFileCallBackAnonimus()
    {
        Byte[] data = new Byte[100];
    
        Console.WriteLine("Основной поток ID = {0}",
           Thread.CurrentThread.ManagedThreadId);
    
        FileStream fs = new FileStream(@"../../Program.cs", FileMode.Open,
                                       FileAccess.Read, FileShare.Read, 1024,
                                       FileOptions.Asynchronous);
    
        fs.BeginRead(data, 0, data.Length, delegate(IAsyncResult ar)
        {
            Console.WriteLine("Чтение в потоке {0} закончено",
            Thread.CurrentThread.ManagedThreadId);
    
            Int32 bytesRead = fs.EndRead(ar);
    
            fs.Close();
    
            Console.WriteLine("Количество считаных байт = {0}", bytesRead);
            Console.WriteLine(Encoding.UTF8.GetString(data).Remove(0, 1));
    
            Console.ReadLine();
        }, null);
        Console.ReadLine();
    }
    
    private static void AsyncReadMultiplyFilesAnonimus()
    {
        string[] files = {"../../Program.cs", 
                          "../../AsyncReadCallBack.csproj", 
                          "../../Properties/AssemblyInfo.cs"};
    
        for (int i = 0; i < files.Length; ++i)
            new AsyncCallBackReader(new FileStream(files[i], FileMode.Open, FileAccess.Read,
                                    FileShare.Read, 1024, FileOptions.Asynchronous), 100,
                                      delegate(Byte[] data)
                                      {
                                          // Process the data.
                                          Console.WriteLine("Количество прочитаных байт = {0}", data.Length);
                                          Console.WriteLine(Encoding.UTF8.GetString(data).Remove(0, 1) + "\n\n");
                                      });
        Console.ReadLine();
    }
    

    }

    public delegate void AsyncBytesReadDel(Byte[] streamData);

    class AsyncCallBackReader { FileStream stream; byte[] data; IAsyncResult asRes; AsyncBytesReadDel callbackMethod;

    public AsyncCallBackReader(FileStream s, int size, AsyncBytesReadDel meth)
    {
        stream = s;
        data = new byte[size];
        callbackMethod = meth;
        asRes = s.BeginRead(data, 0, size, ReadIsComplete, null);
    }
    
    public void ReadIsComplete(IAsyncResult ar)
    {
        int countByte = stream.EndRead(asRes);
        stream.Close();
        Array.Resize(ref data, countByte);
        callbackMethod(data);
    }
    

    } }

    "

  2. Assistant

    Ниже приведён полный проект Windows Forms на C#, который реализует асинхронное чтение файлов с демонстрацией подходов из вашего кода. Вместо жестко прописанных путей здесь используется стандартный диалог выбора файлов (OpenFileDialog). Все операции чтения выполняются асинхронно с обратными вызовами, а результаты отображаются в TextBox формы.


    Структура проекта

    AsyncReadCallBackWinForms/
    │
    ├── AsyncReadCallBackWinForms.csproj
    ├── Program.cs
    ├── AsyncCallBackReader.cs
    └── MainForm.cs
    └── MainForm.Designer.cs
    

    1. AsyncReadCallBackWinForms.csproj

    <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
      <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>net6.0-windows</TargetFramework>
        <UseWindowsForms>true</UseWindowsForms>
        <RootNamespace>AsyncReadCallBackWinForms</RootNamespace>
      </PropertyGroup>
    </Project>
    

    2. Program.cs

    Точка входа приложения.

    using System;
    using System.Windows.Forms;
    
    namespace AsyncReadCallBackWinForms
    {
        static class Program
        {
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm());
            }
        }
    }
    

    3. AsyncCallBackReader.cs

    Вспомогательный класс для асинхронного чтения файла и вызова callback с прочитанными данными.

    using System;
    using System.IO;
    
    namespace AsyncReadCallBackWinForms
    {
        public delegate void AsyncBytesReadDel(byte[] streamData);
    
        class AsyncCallBackReader
        {
            private readonly FileStream stream;
            private byte[] data;
            private IAsyncResult asRes;
            private readonly AsyncBytesReadDel callbackMethod;
    
            public AsyncCallBackReader(FileStream s, int size, AsyncBytesReadDel meth)
            {
                stream = s;
                data = new byte[size];
                callbackMethod = meth;
                asRes = stream.BeginRead(data, 0, size, ReadIsComplete, null);
            }
    
            private void ReadIsComplete(IAsyncResult ar)
            {
                int countByte = stream.EndRead(asRes);
                stream.Close();
                Array.Resize(ref data, countByte);
                callbackMethod(data);
            }
        }
    }
    

    4. MainForm.cs

    Основная форма приложения с элементами управления и логикой вызова асинхронного чтения файлов.

    using System;
    using System.IO;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    
    namespace AsyncReadCallBackWinForms
    {
        public partial class MainForm : Form
        {
            public MainForm()
            {
                InitializeComponent();
            }
    
            private void btnReadOneFile_Click(object sender, EventArgs e)
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Title = "Выберите файл для чтения (AsyncReadOneFileCallBack)";
                if (ofd.ShowDialog() != DialogResult.OK) return;
    
                textBoxOutput.Clear();
    
                byte[] staticData = new byte[100];
                textBoxOutput.AppendText($"Основной поток ID = {Thread.CurrentThread.ManagedThreadId}\r\n");
    
                FileStream fs = new FileStream(ofd.FileName, FileMode.Open,
                                               FileAccess.Read, FileShare.Read, 1024,
                                               FileOptions.Asynchronous);
    
                fs.BeginRead(staticData, 0, staticData.Length, ReadIsComplete, fs);
    
                void ReadIsComplete(IAsyncResult ar)
                {
                    if (InvokeRequired)
                    {
                        BeginInvoke(new Action<IAsyncResult>(ReadIsComplete), ar);
                        return;
                    }
    
                    textBoxOutput.AppendText($"Чтение в потоке {Thread.CurrentThread.ManagedThreadId} закончено\r\n");
    
                    FileStream stream = (FileStream)ar.AsyncState;
                    int bytesRead = stream.EndRead(ar);
                    stream.Close();
    
                    textBoxOutput.AppendText($"Количество считаных байт = {bytesRead}\r\n");
                    string text = Encoding.UTF8.GetString(staticData, 0, bytesRead);
    
                    if(text.Length > 1)
                        text = text.Remove(0, 1);
    
                    textBoxOutput.AppendText(text + "\r\n");
                }
            }
    
            private void btnReadOneFileAnon_Click(object sender, EventArgs e)
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Title = "Выберите файл для чтения (AsyncReadOneFileCallBackAnonimus)";
                if (ofd.ShowDialog() != DialogResult.OK) return;
    
                textBoxOutput.Clear();
    
                byte[] data = new byte[100];
    
                textBoxOutput.AppendText($"Основной поток ID = {Thread.CurrentThread.ManagedThreadId}\r\n");
    
                FileStream fs = new FileStream(ofd.FileName, FileMode.Open,
                                               FileAccess.Read, FileShare.Read, 1024,
                                               FileOptions.Asynchronous);
    
                fs.BeginRead(data, 0, data.Length, delegate (IAsyncResult ar)
                {
                    if (InvokeRequired)
                    {
                        BeginInvoke(new Action<IAsyncResult>(delegate (IAsyncResult arInner)
                        {
                            EndReadCallback(arInner);
                        }), ar);
                    }
                    else
                    {
                        EndReadCallback(ar);
                    }
    
                    void EndReadCallback(IAsyncResult arInner)
                    {
                        int bytesRead = fs.EndRead(arInner);
                        fs.Close();
    
                        textBoxOutput.AppendText($"Чтение в потоке {Thread.CurrentThread.ManagedThreadId} закончено\r\n");
                        textBoxOutput.AppendText($"Количество считаных байт = {bytesRead}\r\n");
    
                        string s = Encoding.UTF8.GetString(data, 0, bytesRead);
                        if (s.Length > 1) s = s.Remove(0, 1);
    
                        textBoxOutput.AppendText(s + "\r\n");
                    }
                }, null);
            }
    
            private void btnReadMultipleFiles_Click(object sender, EventArgs e)
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Title = "Выберите файлы для чтения (AsyncReadMultiplyFilesAnonimus)";
                ofd.Multiselect = true;
                ofd.Filter = "Все файлы|*.*";
                if (ofd.ShowDialog() != DialogResult.OK) return;
    
                textBoxOutput.Clear();
    
                string[] files = ofd.FileNames;
    
                foreach (string file in files)
                {
                    FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read,
                                                   FileShare.Read, 1024, FileOptions.Asynchronous);
    
                    new AsyncCallBackReader(fs, 100, delegate (byte[] data)
                    {
                        if (InvokeRequired)
                        {
                            BeginInvoke(new Action<byte[]>(ProcessData), data);
                        }
                        else
                        {
                            ProcessData(data);
                        }
                    });
                }
    
                void ProcessData(byte[] data)
                {
                    textBoxOutput.AppendText($"Количество прочитаных байт = {data.Length}\r\n");
                    string s = Encoding.UTF8.GetString(data);
                    if(s.Length > 1) s = s.Remove(0,1);
                    textBoxOutput.AppendText(s + "\r\n\r\n");
                }
            }
        }
    }
    

    5. MainForm.Designer.cs

    Дизайнер формы с тремя кнопками и одним многострочным текстовым полем для вывода результатов.

    namespace AsyncReadCallBackWinForms
    {
        partial class MainForm
        {
            private System.ComponentModel.IContainer components = null;
    
            protected override void Dispose(bool disposing)
            {
                if(disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
    
            #region Код, автоматически созданный конструктором форм Windows
    
            private void InitializeComponent()
            {
                this.btnReadOneFile = new System.Windows.Forms.Button();
                this.btnReadOneFileAnon = new System.Windows.Forms.Button();
                this.btnReadMultipleFiles = new System.Windows.Forms.Button();
                this.textBoxOutput = new System.Windows.Forms.TextBox();
                this.SuspendLayout();
                // 
                // btnReadOneFile
                // 
                this.btnReadOneFile.Location = new System.Drawing.Point(12, 12);
                this.btnReadOneFile.Name = "btnReadOneFile";
                this.btnReadOneFile.Size = new System.Drawing.Size(250, 30);
                this.btnReadOneFile.TabIndex = 0;
                this.btnReadOneFile.Text = "AsyncReadOneFileCallBack";
                this.btnReadOneFile.UseVisualStyleBackColor = true;
                this.btnReadOneFile.Click += new System.EventHandler(this.btnReadOneFile_Click);
                // 
                // btnReadOneFileAnon
                // 
                this.btnReadOneFileAnon.Location = new System.Drawing.Point(268, 12);
                this.btnReadOneFileAnon.Name = "btnReadOneFileAnon";
                this.btnReadOneFileAnon.Size = new System.Drawing.Size(250, 30);
                this.btnReadOneFileAnon.TabIndex = 1;
                this.btnReadOneFileAnon.Text = "AsyncReadOneFileCallBackAnonimus";
                this.btnReadOneFileAnon.UseVisualStyleBackColor = true;
                this.btnReadOneFileAnon.Click += new System.EventHandler(this.btnReadOneFileAnon_Click);
                // 
                // btnReadMultipleFiles
                // 
                this.btnReadMultipleFiles.Location = new System.Drawing.Point(524, 12);
                this.btnReadMultipleFiles.Name = "btnReadMultipleFiles";
                this.btnReadMultipleFiles.Size = new System.Drawing.Size(250, 30);
                this.btnReadMultipleFiles.TabIndex = 2;
                this.btnReadMultipleFiles.Text = "AsyncReadMultiplyFilesAnonimus";
                this.btnReadMultipleFiles.UseVisualStyleBackColor = true;
                this.btnReadMultipleFiles.Click += new System.EventHandler(this.btnReadMultipleFiles_Click);
                // 
                // textBoxOutput
                // 
                this.textBoxOutput.Location = new System.Drawing.Point(12, 58);
                this.textBoxOutput.Multiline = true;
                this.textBoxOutput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
                this.textBoxOutput.Name = "textBoxOutput";
                this.textBoxOutput.ReadOnly = true;
                this.textBoxOutput.Size = new System.Drawing.Size(762, 390);
                this.textBoxOutput.TabIndex = 3;
                // 
                // MainForm
                // 
                this.ClientSize = new System.Drawing.Size(786, 460);
                this.Controls.Add(this.textBoxOutput);
                this.Controls.Add(this.btnReadMultipleFiles);
                this.Controls.Add(this.btnReadOneFileAnon);
                this.Controls.Add(this.btnReadOneFile);
                this.Name = "MainForm";
                this.Text = "AsyncReadCallBack (Windows Forms)";
                this.ResumeLayout(false);
                this.PerformLayout();
            }
    
            #endregion
    
            private System.Windows.Forms.Button btnReadOneFile;
            private System.Windows.Forms.Button btnReadOneFileAnon;
            private System.Windows.Forms.Button btnReadMultipleFiles;
            private System.Windows.Forms.TextBox textBoxOutput;
        }
    }
    

    Инструкция по запуску

    1. Создайте проект Windows Forms с .NET 6 или новее.
    2. Создайте соответствующие файлы и вставьте код из примера.
    3. Запустите приложение.
    4. Используйте кнопки для выбора файлов и чтения их асинхронно. Результаты выводятся в TextBox.

    Если нужно, могу помочь с более современным вариантом на async/await или с добавлением прогресс-баров и обработкой ошибок.