2011-11-29 59 views
-2

我想在C#中的特定文件夾的文件名。如何獲取文件夾的文件名在C#

我使用下面的代碼

string[] filePaths = Directory.GetFiles(@"c:\MyDir\"); 

我不想使用GetFiles的功能,因爲它通過process.I鎖定想要的只是文件名,而不是整個路徑。

我該怎麼做?

這是我的完整代碼。

protected void Button1_Click(object sender, EventArgs e) 
{ 
    if (Directory.Exists(Server.MapPath("Import\\"))) 
    { 
     if (FileUpLoad1.HasFile) 
      try 
      { 
       FileUpLoad1.SaveAs(Server.MapPath("Import\\" + FileUpLoad1.FileName)); 
       Label1.Text = FileUpLoad1.FileName; 
      } 
      catch (Exception ex) 
      { 
       Label1.Text = "ERROR: " + ex.Message.ToString(); 
      } 
     else 
     { 
      Label1.ForeColor = System.Drawing.Color.Red; 
      Label1.Text = "No File Uploaded."; 
     } 
    } 
    else 
    { 
     DirectoryInfo di = Directory.CreateDirectory(Server.MapPath("Import\\")); 
     if (FileUpLoad1.HasFile) 
      try 
      { 
       FileUpLoad1.SaveAs(Server.MapPath("Import\\" + FileUpLoad1.FileName)); 
       Label1.Text = FileUpLoad1.FileName; 
      } 
      catch (Exception ex) 
      { 
       Label1.Text = "ERROR: " + ex.Message.ToString(); 
      } 
     else 
     { 
      Label1.ForeColor = System.Drawing.Color.Red; 
      Label1.Text = "No File Uploaded."; 
     } 
    } 
} 

protected void Button2_Click(object sender, EventArgs e) 
{ 
    string[] filePaths = Directory.GetFiles(Server.MapPath("Import")); 
    PdfDocument pdfDoc = new PdfDocument(); 

     foreach (var item in filePaths) 
     { 
      PdfPage pdfPage = new PdfPage(); 
      pdfPage.Size = PageSize.Letter; 
      pdfDoc.Pages.Add(pdfPage); 
      using (var pdfGfx = XGraphics.FromPdfPage(pdfPage)) 
      { 
       pdfGfx.DrawImage(XImage.FromFile(item), 0, 0); 
      } 
     } 

     pdfDoc.Save(Server.MapPath("PDF\\")+ "vivek.pdf"); 
     pdfDoc.Dispose(); 
     pdfDoc.Close(); 

     Label1.Text = "pdf sucessfully created."; 

} 

protected void Button3_Click(object sender, EventArgs e) 
{ 
    System.IO.Directory.Delete(Server.MapPath("Import\\"),true); 
} 

按鈕1是進口和 按鈕2是創建JPG PDF和 按鈕3是用於刪除JPG文件

+0

您忘記了導致被進程鎖定的代碼* – V4Vendetta

+0

您是否嘗試過任何操作? –

+1

向我們展示代碼,否則我們可能會建議您已認爲無法使用的代碼。 –

回答

0
DirectoryInfo di = new DirectoryInfo(@"c:\MyDir\"); 
FileInfo [] files = di.GetFiles(); 

files[0].Name ... // this is just name of the file 
files[0].FullName ... // this is the full pathname of the file  
files[0].Delete(); // will delete first of the files in list - just example 
6

您可以使用下面的代碼來獲得的名稱沒有完整路徑的文件

DirectoryInfo dirInfo = new DirectoryInfo(@"c:\MyDir\"); 
List<string> filenames = dirInfo.GetFiles().Select(i => i.Name).ToList(); 
相關問題