C# 从文件夹中获取特定文件
我有这个文件夹,我想从中获取一个特定的文件,鉴于其中可能有多个文件,我如何才能做到这一点 我尝试过使用C# 从文件夹中获取特定文件,c#,asp.net-mvc,C#,Asp.net Mvc,我有这个文件夹,我想从中获取一个特定的文件,鉴于其中可能有多个文件,我如何才能做到这一点 我尝试过使用StartsWith但无法做到,有没有办法做到这一点 该文件位于CustomerWorkSheet文件夹中,其名称以customer id字段值开头。如果我有以下路径,我应该使用什么:../uploads/attachments/CustomerWorkSheet/**此处的文件名** IWordDocument doc = new WordDocument(); doc.Open(
StartsWith
但无法做到,有没有办法做到这一点
该文件位于CustomerWorkSheet
文件夹中,其名称以customer id
字段值开头。如果我有以下路径,我应该使用什么:../uploads/attachments/CustomerWorkSheet/**此处的文件名**
IWordDocument doc = new WordDocument();
doc.Open(
System.Web.HttpContext.Current.Server.MapPath
("~/Content/uploads/attachments/CustomerWorkSheet/"),
FormatType.Doc);
我需要这样的东西
if(file.StartsWith(customerId))
但无法获取文件
var directoryPath = System.Web.HttpContext.Current.Server.MapPath("~/Content/uploads/attachments/CustomerWorkSheet");
var file = Directory.EnumerateFiles(directoryPath).SingleOrDefault(f => f.Contains("CustomerWorkSheet/" + myCustomerId));
if(file != null){
IWordDocument doc = new WordDocument();
doc.open(file, FormatType.Doc);
}
根据您的评论,您正在寻找以下内容:
var filename = myDirectoryFiles.SingleOrDefault(f => f.Contains("CustomerWorkSheet/" + myCustomerId + "."));
您知道扩展名吗?我使用var pattern=uniqueName+“*”;因此,是的,但这并不重要您想使用模式查找文件吗?也就是在我保存文件时,我现在想要的是获取以CustomerId开头的文件,我告诉过您,因为扩展名不重要var matches=Directory.GetFiles(Server.MapPath(“~/Content/uploads/attachments/CustomerWorkSheet”)我知道这一点,但文件名是个问题,如何获取文件名这一个似乎是空的var file=Directory.EnumerateFiles(directoryPath.SingleOrDefault(f=>f.Contains(“CustomerWorkSheet/”+customerId));customerId是它们的,但SingleOrDefault(f=>f.Contains(“CustomerWorkSheet/”)正如我前面解释的,似乎不起作用名称以customerID开头,因此我需要选择以customerID开头的文件的方法rest已经完成。如果(file.StartsWith(customerID))我需要这样的东西但是无法获取文件。请调试并查看EnumerateFiles返回的内容,以查看需要匹配的模式。您可以使用contains,只要将文件夹放在customerId前面,在customerId后面加一个点。路径分隔符可能不是
/
。最好使用path.GetFileName
。