我不确定我在这里做错了什么......但我注意到我的File.Move()没有重命名任何文件.
另外,有人知道在我的第二个循环中,我能够使用路径和清理文件名列表填充我的.txt文件吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//recurse through files. Let user press 'ok' to move onto next step
string[] files = Directory.GetFiles(@"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing", "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
Console.Write(file + "\r\n");
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
//End section
//Regex -- find invalid chars
string pattern = " *[\\~#%&*{}/<>?|\"-]+ *";
string replacement = " ";
Regex regEx = new Regex(pattern);
string[] fileDrive = Directory.GetFiles(@"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing", "*.*", SearchOption.AllDirectories);
List<string> filePath = new List<string>();
//clean out file -- remove the path name so file name only shows
string result;
foreach(string fileNames in fileDrive)
{
result = Path.GetFileName(fileNames);
filePath.Add(result);
}
StreamWriter sw = new StreamWriter(@"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing\File_Renames.txt");
//Sanitize and remove invalid chars
foreach(string Files2 in filePath)
{
try
{
string sanitized = regEx.Replace(Files2, replacement);
sw.Write(sanitized + "\r\n");
System.IO.File.Move(Files2, sanitized);
System.IO.File.Delete(Files2);
}
catch (Exception ex)
{
Console.Write(ex);
}
}
sw.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
}
我对C#非常陌生,并试图编写一个通过特定驱动器进行递归的应用程序,找到无效字符(如RegEx模式中所指定的),从文件名中删除它们,然后编写一个具有路径名称的.txt文件,更正的文件名.
有任何想法吗?
您的文件路径列表仅包含文件名.您已在调用中删除了目录信息Path.GetFileName(),因此您的File.Move正在应用程序的默认目录中查找目标文件,而不是其原始位置.
我认为您保存已清理文件名的代码是正确的.您应该使用using()StreamWriter周围的构造,如下所示,以确保文件在完成后关闭.
//clean out file -- remove the path name so file name only shows
string result;
foreach(string fileNames in fileDrive)
{
// result = Path.GetFileName(fileNames); // don't do this.
filePath.Add(fileNames);
}
using (StreamWriter sw = new StreamWriter(@"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing\File_Renames.txt"))
{
//Sanitize and remove invalid chars
foreach(string Files2 in filePath)
{
try
{
string filenameOnly = Path.GetFileName(Files2);
string pathOnly = Path.GetDirectoryName(Files2);
string sanitizedFilename = regEx.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFilename);
sw.Write(sanitized + "\r\n");
System.IO.File.Move(Files2, sanitized);
}
catch
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4359 次 |
| 最近记录: |