c# 文件读取,移动,复制
读取文件夹下所有文件
//1.读取path路径下所有文件
DirectoryInfo root = new DirectoryInfo(path);
FileInfo[] files = root.GetFiles();
读取文件内容
//2.读取文件内容 FullName为文件完整路径 实例:E:\EDI\text.txt
string str = System.IO.File.ReadAllText(FullName);
创建目录
1.将字符串rPath映射为真实路径(路径不存在自动创建)
string newPath = System.IO.Path.Combine(rPath);
System.IO.Directory.CreateDirectory(newPath);
2.将两个字符串组合成一个路径。(即在rPath目录下,新建目录(目录名为:新建目录名))
string newPath = System.IO.Path.Combine(rPath,新建目录名);
System.IO.Directory.CreateDirectory(newPath);
字符串保存为文件,输出到指定目录
//将strTest 字符串保存为文件,输出至指定rPath路径(rPath路径需真实存在,示例:E:\EDI\ELN\结果文件名.txt)
strTest = "测试信息";
System.IO.File.WriteAllText(@rPath, strTest, Encoding.UTF8);
c# 移动文件位置
//移动文件位置
//新建目录 存放被移动文件
string newMovePath = System.IO.Path.Combine(D:\text);
System.IO.Directory.CreateDirectory(newMovePath);
//移动文件到指定位置
//FullName:文件原目录 示例: D:\text
//newMovePath:移动到目录(文件新目录\文件名) 示例: D:\text\text.txt
File.Move(@FullName, @newMovePath);
//复制文件到指定位置
//FullName:文件原目录 示例: D:\text
//newMovePath:复制到目录(文件新目录\文件名) 示例: D:\text\text.txt
File.Copy(@FullName, @newMovePath);
实例:
/// <summary>
///
/// </summary>
/// <param name="path">被解析文件 所在路径(路径格式实例:E:\EDI SAMPLE\ELN)</param>
/// <param name="rPath">结果文件 存放路径(默认存放至D盘根目录, 路径格式实例:E:\EDI SAMPLE\)</param>
/// <returns></returns>
public string Readfill(string path, string rPath = @"D:\")
{
try
{
//读取path路径下所有文件
DirectoryInfo root = new DirectoryInfo(path);
FileInfo[] files = root.GetFiles();
int C = 0;
string strTest = DateTime.Now.ToString("F") + "\n" + "\n";
foreach (var item in files)
{
//读取文件内容
string str = System.IO.File.ReadAllText(item.FullName);
//
//从指定字符处 分割字符串
string[] strArray = str.Split(new string[] { "UNB+UNOC:3" }, StringSplitOptions.RemoveEmptyEntries);
//分割后,截取需要数据
string cs = strArray[1].Substring(1, 13) + ":" + strArray[1].Substring(18, 13);
// 结果数据 拼接文本
strTest += "目录" + item.DirectoryName + "下第" + ++C + "个文件" + "\n" +
"文件名为:'" + item.FullName + "'" + "\n" +
"解析内容为:'" + cs + "'" + "\n" + "\n" + "\n";
//移动文件位置
新建目录 存放被移动文件
//string newMovePath = System.IO.Path.Combine(item.DirectoryName + "_Move"+ "\\"+DateTime.Now.ToString("yyyy-MM-dd"));
//System.IO.Directory.CreateDirectory(newMovePath);
File.Copy(item.FullName, newMovePath+item.Name);
将文件 移动至新文件夹下
//File.Move(item.FullName, newMovePath+"\\" + item.Name);
}
//结果文件存放位置
//在指定目录{rPath}下,新建目录{DateTime.Now.ToString("yyyy-MM-dd")}
string newPath = System.IO.Path.Combine(rPath,DateTime.Now.ToString("yyyy-MM-dd"));
System.IO.Directory.CreateDirectory(newPath);
//将结果输出至指定rPath路径
System.IO.File.WriteAllText(newPath + "\\" + DateTime.Now.ToString(" yyyymmddhhmmss") + "读取结果.txt", strTest, Encoding.UTF8);
return "执行成功";
}
catch (Exception ex)
{
return "执行失败" + ex.Message;
}
}