如何在c#中获取文件夹的文件名

时间:2011-11-29 09:21:36

标签: c# asp.net file file-upload file-io

我想要c#中的特定文件夹的文件名。

我正在使用以下代码

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

我不想使用getfiles函数,因为它被进程锁定。我只想要文件名,而不是整个路径。

我该怎么做?

这是我的完整代码。

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文件

2 个答案:

答案 0 :(得分:6)

您可以使用以下代码获取没有完整路径的文件名称

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

答案 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