如何获取应用实例运行期间指定目录下的新创建文件列表?
Nice question—tracking files created after your app launches is a common use case, and there are a couple of solid approaches depending on whether you want to check after the fact or monitor in real-time. Let's walk through both:
The foundational idea is straightforward:
- Capture a timestamp the moment your application starts (stick with UTC time to avoid timezone or daylight saving conflicts).
- For "after-the-fact" checks: Iterate over the target directory and filter files where their creation time is later than your app's start timestamp.
- For real-time tracking: Use a file system watcher to listen for new file creation events as they happen, starting right when your app boots.
C# (.NET) - After-the-Fact Check
This example grabs the app's start time, then scans the directory for files created post-launch:
using System; using System.IO; using System.Collections.Generic; class Program { static void Main() { // Capture app start time in UTC to avoid timezone issues DateTime appStartTimeUtc = DateTime.UtcNow; string targetDirectory = @"C:\Your\Target\Directory"; try { // Get all files (add SearchOption.AllDirectories to include subfolders) string[] allFiles = Directory.GetFiles(targetDirectory, "*.*", SearchOption.TopDirectoryOnly); // Filter files created after app launched List<string> newFiles = new(); foreach (var file in allFiles) { if (File.GetCreationTimeUtc(file) > appStartTimeUtc) { newFiles.Add(file); } } // Output results Console.WriteLine($"Files created after app launch:"); foreach (var file in newFiles) { Console.WriteLine(Path.GetFileName(file)); } } catch (DirectoryNotFoundException) { Console.WriteLine("Error: Target directory does not exist."); } catch (UnauthorizedAccessException) { Console.WriteLine("Error: No permission to access the target directory."); } } }
Python - After-the-Fact Check
Note: Unix-like systems (Linux/macOS) treat os.path.getctime() as "change time" (last metadata update), so we use birth time for true creation time where possible:
import os import time def get_post_launch_files(target_dir): # Capture app start timestamp (UTC-based) app_start_ts = time.time() new_files = [] for root, _, files in os.walk(target_dir): for file in files: file_path = os.path.join(root, file) try: # Handle cross-platform creation time differences if os.name == 'nt': # Windows creation_ts = os.path.getctime(file_path) else: # Linux/macOS stat = os.stat(file_path) try: creation_ts = stat.st_birthtime except AttributeError: # Fallback to modification time if birth time isn't available creation_ts = stat.st_mtime if creation_ts > app_start_ts: new_files.append(file_path) except FileNotFoundError: # Skip files deleted mid-scan continue return new_files # Usage target_directory = "/your/target/directory" files = get_post_launch_files(target_directory) print("Files created after app launch:") for f in files: print(os.path.basename(f))
If you need to track files as they're created (instead of scanning later), use a file system watcher. Here's a C# example:
using System; using System.IO; using System.Collections.Generic; class Program { static readonly List<string> _newlyCreatedFiles = new(); static void Main() { string targetDirectory = @"C:\Your\Target\Directory"; using var watcher = new FileSystemWatcher(targetDirectory); // Subscribe to file creation events watcher.Created += OnFileCreated; watcher.EnableRaisingEvents = true; Console.WriteLine("Monitoring for new files. Press 'q' to exit."); while (Console.Read() != 'q') ; // Print collected files on exit Console.WriteLine("\nFiles created during app runtime:"); foreach (var file in _newlyCreatedFiles) { Console.WriteLine(Path.GetFileName(file)); } } private static void OnFileCreated(object sender, FileSystemEventArgs e) { // Add newly created file to our list _newlyCreatedFiles.Add(e.FullPath); Console.WriteLine($"New file detected: {e.Name}"); } }
- Timezone Consistency: Always use UTC timestamps to avoid issues with daylight saving changes or server timezone mismatches.
- File Deletion: If a file is created then deleted before your scan, it won't show up—real-time monitoring avoids this gap.
- Permission Issues: Ensure your app has read access to the target directory (and subdirectories if scanning recursively).
- Large Directories: Scanning huge directories after the fact can be slow; real-time monitoring is far more efficient for this scenario.
内容的提问来源于stack exchange,提问作者DotNetSpartan

