获取文件夹中的文件
//获取文件夹中的所有文件
string[] dirs = System.IO.Directory.GetFileSystemEntries(filepath + "\\DataCenterImage");
int length=dirs.length;//可获取问价夹中的文件的数量
//可循环遍历获取文件的名称
for (int i = 0; i < dirs .Count; i++)
{
sb.AppendLine(list[i].ToString());
}
MessageBox.Show(sb.ToString());
获取文件下指定格式的文件
DirectoryInfo TheFolder = new DirectoryInfo(@"C:\SENData");
FileInfo[] fileInfo = TheFolder.GetFiles("*.xml");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < fileInfo.Length; i++)
{
sb.AppendLine(fileInfo[i].ToString());
}
判断文件、文件夹是否存在
private void IfHaveFile()
{
//判断是否存在文件
string MyfileNname = "F:\\wentextggg.txt";
if (MyfileNname.Length < 1)
return;
if (File.Exists(MyfileNname)) //调用File.Exists(string)方法判断是否存在
{
Response.Write("文件存在!<br/><br/>");
}
else
{
Response.Write("文件不存在!<br/><br/>");
}
//判断是否存在文件
//MessageBox.Show(pt);
if (Directory.Exists(MyfileNname ))//创建文件夹,如果不存在则创建
{
Response.Write("文件夹存在!<br/><br/>");
}
}
新建文件
string filepath = Application.StartupPath.ToString();//这里我是获取的项目的路径
//MessageBox.Show(pt);
if (!Directory.Exists(filepath + "\\DataCenterImage"))//创建文件夹,如果不存在则创建
{
Directory.CreateDirectory(filepath + "\\DataCenterImage");
}
删除文件夹
/// <summary>
/// 清空指定文件夹,但不删除文件夹
/// </summary>
/// <param name="dir">路径</param>
public static void DeleteFolder(string dir)
{
if (Directory.Exists(dir))
{
foreach (string d in Directory.GetFileSystemEntries(dir))
{
if (File.Exists(d))
{
FileInfo fi = new FileInfo(d);
if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
fi.Attributes = FileAttributes.Normal;
File.Delete(d);//直接删除其中的文件
}
else
{
DirectoryInfo d1 = new DirectoryInfo(d);
if (d1.GetFiles().Length != 0)
{
DeleteFolder(d1.FullName);递归删除子文件夹
}
Directory.Delete(d);
}
}
}
}
/// <summary>
///直接删除指定目录下的所有文件及文件夹
/// </summary>
/// <param name="strPath">文件夹路径</param>
/// <returns>执行结果</returns>
public static void DeleteDir(string file)
{
try
{
//去除文件夹和子文件的只读属性
//去除文件夹的只读属性
System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
//去除文件的只读属性
System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);
//判断文件夹是否还存在
if (Directory.Exists(file))
{
foreach (string f in Directory.GetFileSystemEntries(file))
{
if (File.Exists(f))
{
//如果有子文件删除文件
File.Delete(f);
Console.WriteLine(f);
}
else
{
//循环递归删除子文件夹
DeleteDir(f);
}
}
//删除空文件夹
Directory.Delete(file);
}
}
catch (Exception ex) // 异常处理
{
Console.WriteLine(ex.Message.ToString());// 异常信息
}
}
获取某文件夹的文件列表,并按文件的创建时间排序
引入命名空间
using System.IO;
using System.Collections;
public class FileComparer : IComparer
{
int IComparer.Compare(Object o1, Object o2)
{
FileInfo fi1 = o1 as FileInfo;
FileInfo fi2 = o2 as FileInfo;
return fi1.CreationTime.CompareTo(fi2.CreationTime);
}
}
public class MyClass
{
public FileInfo[] GetFiles(string path)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles();
FileComparer fc = new FileComparer();
Array.Sort(files, fc);
return files;
}
}
调用
FileInfo[] a = new MyClass().GetFiles(@"D:\data");
C#读写文本文件
C#中读写文本文件.txt文件既可以用File类也可用StreamReader、StreamWrite类。这两种方法都需要引用using System.IO命名空间。
下面分别给出例子:
1.File类写入文本文件(追加换行):
private void btnTextWrite_Click(object sender, EventArgs e)
{
//文件路径
string filePath = @"E:\123\456.txt";
if (Directory.Exists(filePath )){
//检测文件夹是否存在,不存在则创建
FileStream fs = File.Create(filePath);//创建文件
fs.Close();
}
//定义编码方式,text1.Text为文本框控件中的内容
byte[] mybyte = Encoding.UTF8.GetBytes(text1.Text);
string mystr1 = Encoding.UTF8.GetString(mybyte + "\r\n" );
//写入文件
//File.WriteAllBytes(filePath,mybyte);//写入新文件
//File.WriteAllText(filePath, mystr1);//写入新文件
File.AppendAllText(filePath, mystr1);//添加至文件
}
2.File类读取文本文件:
private void btnTexRead_Click(object sender, EventArgs e)
{
//文件路径
string filePath = @"E:\123\456.txt";
try
{
if (File.Exists(filePath))
{
StreamReader sR = new StreamReader(filepath, System.Text.Encoding.Default);
return sR.ReadToEnd();//下边方式如果文件编码跟要转的编码不一致会出现乱码,直接用默认编码读取
//StreamReader reader = new StreamReader(txtUrl, Encoding.GetEncoding(“gb2312”));//默认编码不行则使用gb2312
//text1.Text = File.ReadAllText(filePath);
//byte[] mybyte = Encoding.UTF8.GetBytes(text1.Text);
//text1.Text = Encoding.UTF8.GetString(mybyte);
}
else
{
MessageBox.Show("文件不存在");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
3.StreamWrite类写入文本文件:
private void btnTextWrite_Click(object sender, EventArgs e)
{
//文件路径
string filePath = @"E:\123\456.txt";
try
{
//检测文件夹是否存在,不存在则创建
string mystr1 = NiceFileProduce.CheckAndCreatPath(NiceFileProduce.DecomposePathAndName(filePath, NiceFileProduce.DecomposePathEnum.PathOnly));
using (StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8))
{
byte[] mybyte = Encoding.UTF8.GetBytes(text1.Text);
text1.Text = Encoding.UTF8.GetString(mybyte);
sw.Write(text1.Text);
}
}
catch
{
}
}
4.StreamReader类读取文本文档:
private void btnTexRead_Click(object sender, EventArgs e)
{
//文件路径
string filePath = @"E:\123\456.txt";
try
{
if (File.Exists(filePath))
{
using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8))
{
text1.Text = sr.ReadToEnd();
byte[] mybyte = Encoding.UTF8.GetBytes(text1.Text);
text1.Text = Encoding.UTF8.GetString(mybyte);
}
}
else
{
MessageBox.Show("文件不存在");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
复制文件夹中的所有内容到指定文件夹
private static void CopyFile(string srcPath, string aimPath)
{
try
{
// 检查目标目录是否以目录分割字符结束如果不是则添加
if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
{
aimPath += Path.DirectorySeparatorChar;
}
// 判断目标目录是否存在如果不存在则新建
if (!Directory.Exists(aimPath))
{
Directory.CreateDirectory(aimPath);
}
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
// 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
// string[] fileList = Directory.GetFiles(srcPath);
string[] fileList = Directory.GetFileSystemEntries(srcPath);
// 遍历所有的文件和目录
foreach (string file in fileList)
{
// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
if (Directory.Exists(file))
{
CopyFile(file, aimPath + Path.GetFileName(file));
}
// 否则直接Copy文件
else
{
if (File.Exists(file))
{
string 目标 = aimPath + Path.GetFileName(file);
if (!File.Exists(目标))
{//这个判断是为了在复制过程中 被复制的文件正在使用时替换会报错,所以存在就不复制了
File.Copy(file, 目标);
}
}
}
}
}
catch (Exception e)
{
throw;
}
}