如何查找是否在同一台机器上创建了文件?

时间:2015-07-10 07:44:25

标签: c# file filesystems ntfs

我正在使用我的c#应用程序中的文件,每次访问它时都需要检查它的合法性。有没有办法找到该文件是来自另一台计算机还是已在同一台计算机上打包? 我认为有一种标志或者表示该文件来自另一台PC,如下面的截图:

enter image description here

1 个答案:

答案 0 :(得分:3)

此信息存储在Zone.Identifier NTFS Alternate Data Stream中。您可以像普通文件数据一样访问备用数据流(它本身也是一个流 - 一个未命名的数据流):

  • 在命令提示符中,您必须将以:为前缀的流名称附加到文件路径:

    more < some_file.exe:Zone.Identifier

  • 在Powershell中,它是这样的:

    Get-Content -Path some_file.exe -Stream Zone.Identifier

在这两种情况下,如果文件被标记为从外部位置下载,则输出:

[ZoneTransfer]
ZoneId=3

ZoneId的可能有效值及其含义为(from blog entry about ADS):

0 My Computer
1 Local Intranet Zone 
2 Trusted sites Zone 
3 Internet Zone 
4 Restricted Sites Zone 

不幸的是,没有CLR类为ADS提供支持(至少我不知道)。您可以考虑使用these classes或命令行工具Streams,前提是我的Microsoft可以访问它们。

修改 当然,您可以轻松地从C#调用Powershell命令,但这会迫使您的应用程序用户至少拥有Powershell 2.0,可能还有.NET 4.0或更高版本(不确定后者):

    public static void Main(string[] args)
    {
        using (PowerShell powerShellInstance = PowerShell.Create())
        {
            powerShellInstance.AddCommand("Get-Content");
            powerShellInstance.AddParameter("-Path", @"C:\Path\To\File.exe");
            powerShellInstance.AddParameter("-Stream", "Zone.Identifier");

            Collection<PSObject> output = powerShellInstance.Invoke();

            foreach (PSObject obj in output)
            {
                if (obj != null && obj.ToString().StartsWith("ZoneId"))                        
                    Console.WriteLine(obj);                 
            }
        }
    }