如何在C#程序中检查文件大小,以及实现程序自身超限时限制运行或自动销毁?
Hey there! I know you’ve been hunting for solutions to these two problems—let’s break them down with practical, working code examples that you can drop right into your project.
1. Checking File Size in C#
There are two simple, reliable ways to get a file’s size in C#. Pick whichever fits your needs best:
Using File.GetLength() (Quick & Basic)
This method returns the file size directly in bytes. Convert it to megabytes (MB) with a quick calculation:
using System.IO; // Replace with your target file path long fileSizeBytes = File.GetLength(@"C:\Your\File\Path.exe"); // Use 1000.0*1000.0 instead if you prefer decimal MB (vs binary) double fileSizeMB = fileSizeBytes / (1024.0 * 1024.0); Console.WriteLine($"File size: {fileSizeMB:F2} MB");
Using FileInfo (For Extra Metadata)
If you need additional details like creation time or file attributes alongside size, FileInfo is your go-to:
using System.IO; FileInfo fileDetails = new FileInfo(@"C:\Your\File\Path.exe"); long fileSizeBytes = fileDetails.Length; double fileSizeMB = fileSizeBytes / (1024.0 * 1024.0); Console.WriteLine($"File size: {fileSizeMB:F2} MB");
2. Restrict Run or Auto-Delete When Program Exceeds 100MB
First, we need to grab the current program’s own file path, check its size, then trigger the desired action if it crosses the 100MB threshold.
Step 1: Get the Program’s Own Path
Use Assembly to fetch the path of the running EXE:
using System.Reflection; string currentExePath = Assembly.GetExecutingAssembly().Location;
Step 2: Block Execution If Size Is Too Big
If you just want to stop the program from running further, show a message and exit cleanly:
using System; using System.IO; using System.Reflection; class Program { static void Main(string[] args) { string currentExePath = Assembly.GetExecutingAssembly().Location; long fileSizeBytes = new FileInfo(currentExePath).Length; double fileSizeMB = fileSizeBytes / (1024.0 * 1024.0); const double MaxAllowedSizeMB = 100.0; if (fileSizeMB > MaxAllowedSizeMB) { Console.WriteLine($"Error: Program size ({fileSizeMB:F2} MB) exceeds {MaxAllowedSizeMB} MB limit. Exiting..."); Environment.Exit(1); // Non-zero exit code signals failure } // Your normal program logic goes here Console.WriteLine("Program running normally!"); } }
Step 3: Auto-Delete the Program (Workaround for Locked Files)
You can’t delete the EXE while it’s running (Windows locks it). Instead, we’ll create a temporary batch file that deletes the EXE after our program exits:
using System; using System.IO; using System.Reflection; using System.Diagnostics; class Program { static void Main(string[] args) { string currentExePath = Assembly.GetExecutingAssembly().Location; long fileSizeBytes = new FileInfo(currentExePath).Length; double fileSizeMB = fileSizeBytes / (1024.0 * 1024.0); const double MaxAllowedSizeMB = 100.0; if (fileSizeMB > MaxAllowedSizeMB) { Console.WriteLine("Program size exceeds limit. Auto-deleting..."); // Create temp batch file string batchPath = Path.Combine(Path.GetTempPath(), "CleanupExe.bat"); string batchContent = $@" @echo off timeout /t 2 /nobreak > nul // Give program time to exit del ""{currentExePath}"" // Delete the EXE del ""%~f0"" // Delete this batch file "; File.WriteAllText(batchPath, batchContent); // Run batch in hidden window and exit our program Process.Start(new ProcessStartInfo(batchPath) { WindowStyle = ProcessWindowStyle.Hidden }); Environment.Exit(0); } // Normal program logic Console.WriteLine("Program running normally!"); } }
The 2-second timeout ensures our program has fully exited before the batch tries to delete the locked EXE.
内容的提问来源于stack exchange,提问作者Lepis

