获取文本文件路径中的文件名 [英] get files names in path to a text file

查看:53
本文介绍了获取文本文件路径中的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DirectoryInfo Dir = new DirectoryInfo(strpath); 
FileInfo[] FileList = Dir.GetFiles("*.krs*"); 
foreach (FileInfo FI in FileList ) 
{ 
listBox1.Items.Add(FI.Name); //write this list to a text file please help me 
} 

推荐答案

DirectoryInfo dir = new DirectoryInfo(@"D:\Logs\BodyShop.US\Warning");
FileInfo[] fi = dir.GetFiles("*.log");

StreamWriter sw = new StreamWriter(@"C:\test.txt");

foreach (FileInfo f in fi)
{
   listBox1.Items.Add(f.Name);
   sw.WriteLine(f.Name);
}
sw.Close();


使用stringbuilder将列表构建为所需的字符串先写,然后是File.WriteAllText.
Use a stringbuilder to build your list in to a string that you want to write, then File.WriteAllText.


我先尝试这个
using (System.IO.FileStream fs = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None)) 
{
  foreach (FileInfo FI in FileList )
  {
    listBox1.Items.Add(FI.Name);
  
    //write this list to a text file please help me
    byte[] writeFileName = ASCIIEncoding.GetBytes(FI.Name);
    fs.Write(writeFileName, 0, writeFileName.Length);
  }
}

也许ASCIIEncoding不是您想要的,然后尝试另一种编码,例如UTF8Encoding左右.

Maybe ASCIIEncoding is not what you want, then try another encoding like UTF8Encoding or so.


这篇关于获取文本文件路径中的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆