gpt4 book ai didi

c# - 如何在 C# 中测试文件是否是 .Net 程序集

转载 作者:行者123 更新时间:2023-12-02 13:23:07 24 4
gpt4 key购买 nike

我编写了以下代码:

public DataTable GetDotNetAssemblies(string baseDirectory)
{
DataTable MethodResult = null;
try
{
if (Directory.Exists(baseDirectory))
{
List<string> FilePaths = NetworkConnection.GetAllFilesUnderDirectory(baseDirectory);

DataTable dt = new DataTable();
dt.Columns.Add("Directory");
dt.Columns.Add("Filename");
dt.Columns.Add("Date modified");
dt.Columns.Add("Bytes");
dt.Columns.Add("User modified");

foreach (string FilePath in FilePaths)
{
DataRow dr = dt.NewRow();

FileInfo f = new FileInfo(FilePath);

List<string> AllowedExtensions = new List<string>();
AllowedExtensions.Add(".exe");
AllowedExtensions.Add(".dll");

if (AllowedExtensions.Contains(f.Extension.ToLower()))
{
dr["Directory"] = f.Directory;
dr["Filename"] = f.Name;
dr["Date modified"] = f.LastWriteTime;
dr["Bytes"] = f.Length.ToString();

string UserModified = "";

try
{
UserModified = f.GetAccessControl().GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();

}
catch
{
UserModified = "Unknown";

}

dr["User modified"] = UserModified;

dt.Rows.Add(dr);

}

}

dt.AcceptChanges();

MethodResult = dt;

}
else
{
MessageBox.Show("Unable to connect to directory:\n" + baseDirectory);

}

}
catch (Exception ex)
{
ex.HandleException();
}
return MethodResult;
}

我已经按文件扩展名进行过滤,您可以通过以下行看到:

if (AllowedExtensions.Contains(f.Extension.ToLower()))

我需要的是通过检查它们是否是 .Net 程序集来进一步过滤程序集文件。

我可以对文件执行测试吗?

此外,如果能够发现程序集中使用了哪个版本的 .Net CLR,那就更好了。

最佳答案

您可以尝试使用GetAssemblyName()尝试解析它是否是类似于 the technique mentioned in this MSDN documentation 的实际程序集的方法:

public string bool IsValidAssembly(string path)
{
try
{
// Attempt to resolve the assembly
var assembly = GetAssemblyName(path);
// Nothing blew up, so it's an assembly
return true;
}
catch(Exception ex)
{
// Something went wrong, it is not an assembly (specifically a
// BadImageFormatException will be thrown if it could be found
// but it was NOT a valid assembly
return false;
}
}

因此您可以考虑在代码中使用以下内容:

// Check that it is a valid extension and a valid assembly
if (AllowedExtensions.Contains(f.Extension.ToLower()) && IsValidAssembly(FilePath))
{
// At this point it should be valid, so continue
}

关于c# - 如何在 C# 中测试文件是否是 .Net 程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36797939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com