【发布时间】:2015-09-18 05:11:54
【问题描述】:
我有一种情况,用户将在运行时输入文件名(不指定路径)。而且我必须通过c#代码找出文件。
我看到了一个函数GetFullPath(),但它只是给出了当前目录路径,附加了用户在运行时输入的文件名。
string fullPath;
Console.WriteLine("please enter teh name of the file to be searched");
String fileName = Console.ReadLine();
fullPath = Path.GetFullPath(fileName);
c# 中是否存在这样的方法来获取在运行时指定的文件的完整路径? (没有指定路径)。我可以说服用户指定驱动器(C:/D:/E:...),但在运行时编写完整路径以查找该文件,他们不会同意。
编辑:我的尝试是这样的:(但它拒绝访问)如果我不够聪明,无法访问每个目录,请帮助我,并且在我得到我的文件之前不要尝试打开安全文件夹。
public static string Search(string fileName)
{
string fullPath = string.Empty;
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity);
if (currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
try
{
foreach (string fpath in Directory.GetFiles("F:\\", "*", SearchOption.AllDirectories))
{
try
{
if (fpath.Substring(fpath.LastIndexOf("\\") + 1).ToUpper().Contains(fileName.ToUpper()))
fullPath = fpath;
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access denied to folder1: " + fullPath);
}
}
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access denied to folder2: " + fullPath);
}
}
else
{
Console.WriteLine("You are not authorized");
}
return fullPath;
}
【问题讨论】:
-
在这种情况下,您必须在用户提供的驱动器的所有目录中查找文件
-
推荐的方法是使用文件选择器或拖放那里可以获得完整的文件路径
-
是的,有(参见“重复”问题)。但根据用户的硬盘大小/速度,这将是一种令人难以置信的烦人体验。