【发布时间】:2013-12-15 18:46:19
【问题描述】:
我想更改 FileInfo 对象当前正在使用的文件。假设我想遍历 1000 个文件。
FileInfo myFile = new FileInfo("myfile.txt");
myFile.ChangeFile("myfile2.txt");
我该怎么做?希望 .FileName =,但它是只读的。
【问题讨论】:
我想更改 FileInfo 对象当前正在使用的文件。假设我想遍历 1000 个文件。
FileInfo myFile = new FileInfo("myfile.txt");
myFile.ChangeFile("myfile2.txt");
我该怎么做?希望 .FileName =,但它是只读的。
【问题讨论】:
你不能那样做。文件名是在构建时指定的,以后不能更改。
【讨论】:
DirectoryInfo.GetFiles()。
你不能在c#中这样做你没有内置函数使用这个函数来代替
private void ChangeFiles(string fPath, string fNewName)
{
string fExt;
string fFromName;
string fToName;
int i = 1;
//copy all files from fPath to files array
FileInfo[] files = new DirectoryInfo(fPath).GetFiles();
//loop through all files
foreach (var f in files)
{
//get the filename without the extension
fFromName = Path.GetFileNameWithoutExtension(f.Name);
//get the file extension
fExt = Path.GetExtension(f.Name);
//set fFromName to the path + name of the existing file
fFromName = string.Format("{0}{1}", fPath, f.Name);
//set the fToName as path + new name + _i + file extension
fToName = string.Format("{0}{1}_{2}{3}", fPath, fNewName,i.ToString(), fExt);
//rename the file by moving to the same place and renaming
File.Move(fFromName, fToName);
//increment i
i++;
}
}
【讨论】: