我的情况是用户将在运行时输入文件的名称(不指定路径)。我必须通过c#代码找出文件。
我见过一个函数GetFullPath()
,但它只是给出了当前用户在运行时输入的fileName附加的目录路径。
string fullPath;
Console.WriteLine("please enter teh name of the file to be searched");
String fileName = Console.ReadLine();
fullPath = Path.GetFullPath(fileName);
c#中是否存在这样的方法来获取运行时指定的文件的完整路径? (没有指定路径)。我可以说服用户指定Drive(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;
}
答案 0 :(得分:1)
如果您要搜索文件,可以使用以下内容搜索所有目录。假设用户输入整个文件名(包括扩展名)和源驱动器/位置。
string fullPath = string.Empty;
Console.WriteLine("please enter the name of the file to be searched");
String fileName = Console.ReadLine();
foreach(string fpath in Directory.GetFiles("C:\\", "*", SearchOption.AllDirectories))
{
if (fpath.Substring(fpath.LastIndexOf("\\") + 1).ToUpper() == fileName.ToUpper())
fullpath = fpath;
}
或者,如果用户输入文件的一部分(不包括扩展名),请使用..
foreach(string fpath in Directory.GetFiles("C:\\", "*", SearchOption.AllDirectories))
{
if (fpath.Substring(fpath.LastIndexOf("\\") + 1).ToUpper().Contains(fileName.ToUpper()))
fullpath = fpath;
}
添加到数组或列表中,可以找到多个结果(路径)。
喜欢这样..
var foundPaths = Directory.GetFiles("C:\\", "*", SearchOption.AllDirectories)
.Where(x => x.ToUpper().Contains(fileName.ToUpper()))
.Select(x => x)
.ToList();
答案 1 :(得分:-1)
我找到了自己的解决方案,我正在进行递归调用,直到我找不到要搜索的文件:
List<string> directories = new List<string>(Directory.GetDirectories(driveName));
string name=null;
foreach(string directry in directories)
{
if (GetFileInformation(directry, out name))
{
try
{
DirSearch(directry, fileName, ref foundVar);
}
catch (System.Exception excpt)
{
Console.WriteLine("from except msg :" + excpt.Message);
if(foundVar==true)
{
break;
}
}
}
}
然后函数定义是:
public static void DirSearch(string sDir, string fileName, ref bool foundVar)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, fileName))
{
if (Path.GetFileName(f) == fileName)
{
Console.WriteLine("directory is and inside it is " + f);
OpenExeFile(f);
foundVar = true;
break;
}
}
DirSearch(d, fileName, ref foundVar);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}