如何指定打开excel文件的stringpath?

我该如何去指定一个打开一个Excel文件的stringpath,知道Excel文件的文件名会一直改变,或者至less将该文件夹中最近保存的Excel文件插入到stringpath中? 例如,

string PATH = @"C:\myFileNameWillAlwaysCHange.xlms or mostRecentFile.xlms"; string connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + PATH + ";Extended Properties=Excel 12.0"; 

我想知道如果文件夹中的Excel文件将是唯一的Excel文件,如果有一种方法来指定该文件夹中的任何(只)Excel文件的path基础,并插入stringpath?

你可以这样做

 string PATH = Directory.GetFiles("C:\", "*.xlms").Single(); string connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + PATH + ";Extended Properties=Excel 12.0"; 

如果您不想在发现更多文件的情况下抛出exception,请将Singlereplace为First
如果不希望在没有匹配的文件的情况下抛出exception,请将Singlereplace为FirstOrDefault并添加一个null检查


编辑

要获取最新的文件:

 string PATH = Directory.GetFiles("C:\", "*.xlms").Select(f => new FileInfo(f)).OrderByDescending(fi => fi.CreationTime).First().FullName 

从我的问题中收集的信息,您正在寻找一个Excel文件的path,该文件应该是给定目录中唯一的这样的文件。 在这种情况下,你可以这样做:

 string path= Directory.GetFiles("C:\YourDirectory", "*.xlms").Single(); string connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0"; 

这将获得在给定目录中给定文件扩展名的文件,然后通过对其执行Single()调用来断言只有一个文件。 如果文件夹中存在多个这样的文件,那么您将得到一个InvalidOperationException

编辑为了得到最近的文件(我select了去创造时间,但你可以使用修改date,如果你宁愿),你可以这样做:

 DirectoryInfo info = new DirectoryInfo("C:\YourDirectory"); string path = info.GetFiles("*.xlms").OrderByDescending (fi => fi.CreationTimeUtc).First().FullName; 

这没有exception处理,所以如果First()调用没有返回任何东西,你需要处理它。

我知道你正在寻找所有的Excel文件在一个文件夹。

这是代码:

  try { string PATH = @"C:\YourFolderPath"; DirectoryInfo Dir = new DirectoryInfo(PATH); FileInfo[] FileList = Dir.GetFiles("*.xls*", SearchOption.AllDirectories ); foreach (FileInfo FI in FileList ) { Console.WriteLine(FI.FullName); } } catch (Exception ex) { Console.WriteLine(ex.Message ); } 

在foreach里面你可以放任何你想要的代码