从目录中获取所有文件名(不包括扩展名)的C#代码

6
我正在寻找一种方法来读取目录路径中所有没有扩展名的txt文件,并将它们存储到一个数组中。我查看过path.getFileNameWithoutExtension,但它只能返回一个文件名。我想要从指定路径中获取所有*.txt文件名。
谢谢。
6个回答

17
Directory.GetFiles(myPath, "*.txt")
    .Select(Path.GetFileNameWithoutExtension)
    .Select(p => p.Substring(1)) //per comment

还有一个要求是我需要删除所有文件名的第一个字符。我该怎么做? - hWorld
一个单个的选择比两个更高效。 - Falanwe
你的问题有点不清楚。 filename.Substring(0,1) 只会给你第一个字符。 filename.Substring(1) 会给你除了第一个字符以外的所有内容。 - David

5

Something like:

String[] fileNamesWithoutExtention = 
Directory.GetFiles(@"C:\", "*.txt")
.Select(fileName => Path.GetFileNameWithoutExtension(fileName))
.ToArray();

应该能解决问题。

1
var files = from f in Directory.EnumerateFiles(myPath, "*.txt")
            select Path.GetFileNameWithoutExtension(f).Substring(1);

1
只需要将它转换为Array[]。
   string targetDirectory = @"C:\...";

// Process the list of files found in the directory. 
   string[] fileEntries = Directory.GetFiles(targetDirectory,  "*.csv").Select(Path.GetFileNameWithoutExtension).Select(p => p.Substring(0)).ToArray();

   foreach (string fileName in fileEntries)
        {
          //Code
        }

0
var filenames = Directory.GetFiles(myPath, "*.txt")
.Select(filename => Path.GetFileNameWithoutExtension(filename).Substring(1));

(在评论中添加了(substring(1))以满足规格要求)

-1
public void getTestReportDocument(string reportid, string extenstype)
{
    try
    {
        string filesName = "";
        if (sqlConn.State == ConnectionState.Closed)
            sqlConn.Open();
        if(extenstype == ".pdf")
        {
            filesName = Path.GetTempFileName();
        }
        else
        {
            filesName = Path.GetTempFileName() + extenstype;
        }

        SqlCommand cmd = new SqlCommand("GetTestReportDocuments", sqlConn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@ReportID", reportid);

        using (SqlDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.Default))
        {
             while (dr.Read())
             {
                 int size = 1024 * 1024;
                 byte[] buffer = new byte[size];
                 int readBytes = 0;
                 int index = 0;
                 using (FileStream fs = new FileStream(filesName, FileMode.Create, FileAccess.Write, FileShare.None))
                 {
                     while ((readBytes = (int)dr.GetBytes(0, index, buffer, 0, size)) > 0)
                     {
                         fs.Write(buffer, 0, readBytes);
                         index += readBytes;
                     }
                 }
             }
        }
        Process prc = new Process();
        prc.StartInfo.FileName = filesName;
        prc.Start();
   }

   catch (Exception ex)
   {
       throw ex;
   }
   finally
   {
       //daDiagnosis.Dispose();
       //daDiagnosis = null;
   }
}

终于我找到了解决方案...希望它能够起作用
输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接