02/10/2018, 11:35

[C#] Hướng dẫn đọc thuộc tính file trong lập trình csharp

Bài viết hôm nay, mình sẽ tiếp tục hướng dẫn các bạn cách đọc thuộc tính thông tin của một file trong lập trình C# . Ví dụ: chúng ta muốn lấy các thông tin cơ bản của một file notepad.exe Bao gồm: File version, File size, Company, File name, ...

Bài viết hôm nay, mình sẽ tiếp tục hướng dẫn các bạn cách đọc thuộc tính thông tin của một file trong lập trình C#.

Ví dụ: chúng ta muốn lấy các thông tin cơ bản của một file notepad.exe

Bao gồm: File version, File size, Company, File name, File Description...

Hình ảnh thông tin file "notepad.exe" như hình bên dưới:

đọc thông tin file lập trình C#

Để đọc các thông tin trên chúng ta sẽ sử dụng thư viện class FileVersionInfo có sẵn trong .NET

Giao diện demo ứng dụng:

file info C#

Source code C#:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FileInfo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StringBuilder a = new StringBuilder(); 
            if(openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                System.IO.FileInfo f = new System.IO.FileInfo(openFileDialog1.FileName);
                long s1 = f.Length;
                var obj = FileVersionInfo.GetVersionInfo(openFileDialog1.FileName);
                a.Append("Name: " + obj.FileName + "
");
                a.Append("File Version: " + obj.FileVersion + "
");
                a.Append("Copyright: " + obj.LegalCopyright + "
");
                a.Append("Original File name: " + obj.OriginalFilename + "
");
                a.Append("Company Name: " + obj.CompanyName + "
");
                a.Append("Language: " + obj.Language + "
");
                a.Append("File size: " + s1 + "
");
                richTextBox1.Text = a.ToString();
               
            }
        }
    }
}

HAVE FUN:)

Tags: đọc fileghi file
0