當我使用下面的代碼行時,我得到一個包含單個文件的完整路徑的字符串數組。如何只使用c#獲取目錄中的文件名?
private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf");
我想知道是否有一種方法只檢索字符串,而不是整個路徑的文件名。
當我使用下面的代碼行時,我得到一個包含單個文件的完整路徑的字符串數組。如何只使用c#獲取目錄中的文件名?
private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf");
我想知道是否有一種方法只檢索字符串,而不是整個路徑的文件名。
您可以使用Path.GetFileName
從完整路徑獲得的文件名
private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf")
.Select(Path.GetFileName)
.ToArray();
編輯:上述解決方案使用LINQ,所以它至少需要.NET 3.5。下面是在較早版本的有效的解決方案:
private string[] pdfFiles = GetFileNames("C:\\Documents", *.pdf");
private static string[] GetFileNames(string path, string filter)
{
string[] files = Directory.GetFiles(path, filter);
for(int i = 0; i < files.Length; i++)
files[i] = Path.GetFileName(files[i]);
return files;
}
您可以使用DirectoryInfo和FileInfo類。
//GetFiles on DirectoryInfo returns a FileInfo object.
var pdfFiles = new DirectoryInfo("C:\\Documents").GetFiles("*.pdf");
//FileInfo has a Name property that only contains the filename part.
var firstPdfFilename = pdfFiles[0].Name;
有這麼多的方法:)
1路:
string[] folders = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
string jsonString = JsonConvert.SerializeObject(folders);
第二路:
string[] folders = new DirectoryInfo(yourPath).GetDirectories().Select(d => d.Name).ToArray();
3路:
string[] folders =
new DirectoryInfo(yourPath).GetDirectories().Select(delegate(DirectoryInfo di)
{
return di.Name;
}).ToArray();
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetNameOfFiles
{
public class Program
{
static void Main(string[] args)
{
string[] fileArray = Directory.GetFiles(@"YOUR PATH");
for (int i = 0; i < fileArray.Length; i++)
{
Console.WriteLine(fileArray[i]);
}
Console.ReadLine();
}
}
}
您好托馬斯,我得到這樣的錯誤\t'System.Array'沒有包含'Select'的定義,也沒有找到接受'System.Array'類型的第一個參數的擴展方法'Select'(你是否缺少使用指令或程序集引用?)\t還有什麼我需要考慮的嗎? –
在文件的開始處添加'using System.Linq;',並在System.Core'程序集中引用它(如果它尚未存在)。它需要.NET 3.5或更高版本,如果你需要的話,我會發布.NET 2.0的解決方案 –
非常感謝Thomas。 –