给定下载来源URL,如何检索本地对应文件,是否有C#实现方案?
实现方案
Windows 下载文件时写入的Zone.Identifier NTFS交换数据流确实存储了来源URL信息,反向查询的核心逻辑是遍历目标路径下的文件,逐个读取对应文件的Zone.Identifier流,匹配ReferrerUrl/HostUrl与目标URL即可得到对应的下载文件。
C# 实现代码
using System; using System.Collections.Generic; using System.IO; using System.Linq; public class ZoneIdentifierSearcher { // 从Zone.Identifier流中获取指定键的值 private static string GetZoneIdentifierValue(string filePath, string key) { var adsPath = $"{filePath}:Zone.Identifier"; if (!File.Exists(adsPath)) return null; try { var lines = File.ReadAllLines(adsPath); var targetLine = lines.FirstOrDefault(l => l.StartsWith($"{key}=")); return targetLine?.Split('=', 2)[1]?.Trim(); } catch { // 无权限、文件被占用等情况直接跳过 return null; } } // 按目标URL搜索匹配的下载文件 public static List<string> SearchFilesByDownloadUrl(string targetUrl, string searchRootPath, bool fuzzyMatch = true) { var result = new List<string>(); if (!Directory.Exists(searchRootPath)) return result; // 遍历目录下所有文件,按需调整SearchOption为AllDirectories递归遍历子目录 var allFiles = Directory.GetFiles(searchRootPath, "*.*", SearchOption.TopDirectoryOnly); foreach (var file in allFiles) { var referrer = GetZoneIdentifierValue(file, "ReferrerUrl"); var host = GetZoneIdentifierValue(file, "HostUrl"); bool isMatch = false; if (fuzzyMatch) { isMatch = (!string.IsNullOrEmpty(referrer) && referrer.Contains(targetUrl)) || (!string.IsNullOrEmpty(host) && host.Contains(targetUrl)); } else { isMatch = string.Equals(referrer, targetUrl, StringComparison.OrdinalIgnoreCase) || string.Equals(host, targetUrl, StringComparison.OrdinalIgnoreCase); } if (isMatch) { result.Add(file); } } return result; } // 调用示例 public static void Main() { var targetUrl = "https://example.com/download"; var searchPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); var matchedFiles = SearchFilesByDownloadUrl(targetUrl, searchPath); Console.WriteLine("匹配到的文件:"); matchedFiles.ForEach(f => Console.WriteLine(f)); } }
注意事项
- 该功能仅支持NTFS文件系统,FAT32、exFAT等不支持ADS特性的文件系统无法使用
- 部分第三方下载工具、自定义配置的浏览器不会写入
Zone.Identifier流,这类文件无法被检索到 - 建议指定具体的搜索目录,避免直接遍历整个磁盘导致检索耗时过长
- 可通过调整
fuzzyMatch参数选择精确匹配或模糊匹配URL,也可自行修改逻辑只匹配ReferrerUrl或HostUrl
内容的提问来源于stack exchange,提问作者user10446660
相关产品推荐
相关产品推荐

