You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中读取本地目录的.exe文件并存入DataTable?

解决C#读取Debug文件夹中.exe文件并存入DataTable的问题

Hey there! As a C# dev who started out just like you, let's work through this problem together. First, I want to clarify: an .exe is a binary executable file, not a tabular data source like Excel. So I'm assuming you want to extract metadata and properties from the .exe files (like version info, file details) and store that structured data in a DataTable—this is the most common use case for this kind of task. Let's break this down step by step.

1. Define What Data You Want to Capture

First, decide what information you need from the .exe files. Common options include:

  • Basic file properties (name, path, size, creation time)
  • Version metadata (company name, product version, file version)
  • PE header details (64-bit/32-bit, entry point address—for more advanced use cases)

2. Step-by-Step Implementation

2.1 Create a DataTable Structure

Start by defining a DataTable with columns that match the data you want to capture:

using System.Data;
using System.IO;
using System.Diagnostics;

// Initialize DataTable with relevant columns
DataTable exeDataTable = new DataTable("ExecutableInfo");
exeDataTable.Columns.Add("FileName", typeof(string));
exeDataTable.Columns.Add("FullFilePath", typeof(string));
exeDataTable.Columns.Add("FileSizeMB", typeof(double));
exeDataTable.Columns.Add("CreationTime", typeof(DateTime));
exeDataTable.Columns.Add("CompanyName", typeof(string));
exeDataTable.Columns.Add("ProductVersion", typeof(string));
exeDataTable.Columns.Add("FileVersion", typeof(string));

2.2 Locate the Debug Folder

Get the path to your project's Debug directory. If this code runs from the same project, you can use the app domain's base directory. If targeting another project's Debug folder, hardcode the path (or make it configurable):

//</think_never_used_51bce0c785ca2f68081bfa7d91973934>Get the Debug folder path for the current running application
string debugDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Debug");

// If targeting a different project's Debug folder, use something like:
// string debugDirectory = @"C:\YourProjectRoot\YourProjectName\bin\Debug";

2.3 Extract Data from Each .exe File

Loop through all .exe files in the Debug folder, extract their properties, and add rows to the DataTable. Add error handling to avoid crashes if files are locked or unreadable:

foreach (string exePath in Directory.GetFiles(debugDirectory, "*.exe"))
{
    try
    {
        // Get basic file info
        FileInfo fileInfo = new FileInfo(exePath);
        
        // Get version metadata
        FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(exePath);

        // Create a new row and populate it
        DataRow newRow = exeDataTable.NewRow();
        newRow["FileName"] = fileInfo.Name;
        newRow["FullFilePath"] = fileInfo.FullName;
        newRow["FileSizeMB"] = Math.Round(fileInfo.Length / (1024.0 * 1024.0), 2); // Convert bytes to MB
        newRow["CreationTime"] = fileInfo.CreationTime;
        newRow["CompanyName"] = string.IsNullOrEmpty(versionInfo.CompanyName) ? "N/A" : versionInfo.CompanyName;
        newRow["ProductVersion"] = string.IsNullOrEmpty(versionInfo.ProductVersion) ? "N/A" : versionInfo.ProductVersion;
        newRow["FileVersion"] = string.IsNullOrEmpty(versionInfo.FileVersion) ? "N/A" : versionInfo.FileVersion;

        // Add the row to the DataTable
        exeDataTable.Rows.Add(newRow);
    }
    catch (Exception ex)
    {
        // Handle errors (e.g., file is in use, permission issues)
        Console.WriteLine($"Failed to process {exePath}: {ex.Message}");
    }
}

2.4 (Optional) Extract Advanced PE Header Info

If you need deeper details about the .exe (like whether it's 64-bit, entry point address), use a library like PeNet (a lightweight .NET PE parser). First install the NuGet package PeNet, then modify the code:

// Add this using statement at the top
using PeNet;

// Inside the loop, add these lines to capture PE info
PeFile peFile = new PeFile(exePath);
newRow["Is64Bit"] = peFile.Is64Bit;
newRow["EntryPointAddress"] = peFile.ImageNtHeaders.OptionalHeader.AddressOfEntryPoint.ToString("X8"); // Hex format

// Don't forget to add these columns to the DataTable earlier!
exeDataTable.Columns.Add("Is64Bit", typeof(bool));
exeDataTable.Columns.Add("EntryPointAddress", typeof(string));

3. Tips for New C# Devs

  • Check Permissions: Make sure your application has read access to the Debug folder.
  • Validate Paths: Use Directory.Exists(debugDirectory) to check if the folder exists before processing.
  • Test with Small Data: Start with a single .exe file to debug your code before looping through all files.

If your original goal was to read the raw binary content of the .exe into a DataTable (e.g., storing each byte as a row), that's a less common scenario—but let me know and I can adjust the solution!

内容的提问来源于stack exchange,提问作者Lazaro R.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:33:51