使用System.IO.File或其他.NET类,重命名文件的最佳方法是什么?
我希望能够重命名本地驱动器或网络位置上的文件.
如果使用System.IO.File,是Move最好的方法吗?
我有以下代码将文件复制到特定文件夹,然后重命名它.当具有该名称的文件已存在时,我收到以下异常:
Cannot create a file when that file already exists
Run Code Online (Sandbox Code Playgroud)
有没有办法覆盖文件并重命名?或者我应该删除旧的然后更改名称?
这是我的代码:
File.Copy(FileLocation, NewFileLocation, true);
//Rename:
File.Move(Path.Combine(NewFileLocation, fileName), Path.Combine(NewFileLocation, "File.txt"));
Run Code Online (Sandbox Code Playgroud) 在阅读了关于如何"重命名"文件的stackoverflow帖子后,解决方案结果是使用Files.Move或Directory.Move方法.
我知道在Windows中,如果我重命名它是瞬间的,因为我认为它不是移动驱动器上的文件,因为它正在改变某些索引的位置.
当我使用Files.Move或Directory.Move它会做同样的事情,还是要做一个复制,然后删除?
我试图避免我的驱动器磨损.
我有一个程序可以将文件或文件夹重命名为小写名称。我写了这段代码:
private void Replace(string FolderLocation, string lastText, string NewText)
{
if (lastText == "")
{
lastText = " ";
}
if (NewText == "")
{
NewText = " ";
}
DirectoryInfo i = new DirectoryInfo(FolderLocation);
string NewName = "";
if (checkBox2.Checked)
{
if (i.Parent.FullName[i.Parent.FullName.Length - 1].ToString() != "\\") //For parents like E:/
{
NewName = i.Parent.FullName + "\\" + i.Name.Replace(lastText, NewText);
}
else
{
NewName = i.Parent.FullName + i.Name.Replace(lastText, NewText);
}
NewName = NewName.ToLower();
if (NewName != i.FullName)
{
i.MoveTo(NewName); …Run Code Online (Sandbox Code Playgroud) if (File.Exists(@"C:\\Users" + Environment.UserName + "\\Desktop\\test"))
{ /\
this file has no file extension
}
Run Code Online (Sandbox Code Playgroud)
该文件test没有扩展名,我需要帮助将此文件移动或重命名为具有扩展名的文件