在使用后面的代码前,需要:
using System;
using System.IO;
C# 对文件的操作
- 判断文件是否存在
string filePath = "E:\\new folder\\test\\myfile.xls";
if (File.Exists(filePath))
{// 如果文件存在
}
else
{// 如果文件不存在
}
- 复制文件
string oldFileName = "E:\\new folder\\test\\myfile.xls";
string newFileName = "E:\\new folder\\test\\myfile_copy.xls";
File.Copy(oldFileName, newFileName, ture); // 将现有文件复制到新文件, 允许覆盖同名的文件。
// File.Copy(oldFileName, newFileName, false); // 将现有文件复制到新文件, 不允许覆盖同名的文件。
- 往 txt 文件中追加内容
string Year = DateTime.Now.Year.ToString(); // 获取当前年份
string Month = DateTime.Now.Month.ToString().PadLeft(2, '0'); // 获取当前月份
string Day = DateTime.Now.Day.ToString().PadLeft(2, '0'); // 获取当前是几号
string Hour = DateTime.Now.Hour.ToString().PadLeft(2, '0');
string Minute = DateTime.Now.Minute.ToString().PadLeft(2, '0');
string Second = DateTime.Now.Second.ToString().PadLeft(2, '0');string filePath = "E:\\new folder\\test\\myfile.txt";
FileStream fs = new FileStream(filePath, FileMode.Append);
StreamWriter wr = null;
wr = new StreamWriter(fs);
wr.WriteLine("Date: " + Year + "." + Month + "." + Day + "\n");
wr.WriteLine("Time: " + Hour + ":" + Minute + ":" + Second + "\n");
wr.Close();
C# 对文件夹的操作
- 获取当前文件夹的路径
string currentWorkPath = System.IO.Directory.GetCurrentDirectory();
// currentWorkPath = "E:\\new folder\\test";
- 创建文件夹
string folderPath = "E:\\new folder\\test";
Directory.CreateDirectory(folderPath);
- 判断文件夹是否存在
string folderPath = "E:\\new folder\\test";
if (Directory.Exists(folderPath))
{// 如果文件夹存在
}
else
{// 如果文件夹不存在
}
- 移动文件夹
string sourceDirectory = @"C:\source";
string destinationDirectory = @"C:\destination";
try
{Directory.Move(sourceDirectory, destinationDirectory);
}
catch (Exception e)
{Console.WriteLine(e.Message);
}
- 读取一个文件夹下所有的 .xls 文件
string folderPath = "E:\\new folder\\test";
string[] files = Directory.GetFiles(folderPath + @"\", "*.xls");
参考
- C#.NET读取一个文件夹下所有excel文件的代码
- 微软 .Net System.IO File.Copy 方法
- 简单到复杂:C#拷贝文件的3种方法