简体   繁体   English

C#将文件重命名为与其他目录中的文件相同的名称

[英]C# rename a file to the same name as a file from a different directory

For example I have 2 directories with both the same file, and when I renamed the file in the 1st directory, it should be renamed in the 2nd directory as well. 例如,我有两个具有相同文件的目录,当我在第一个目录中重命名该文件时,它也应该在第二个目录中重命名。 If the file is renamed in the 2nd directory, I dont want it to be renamed in the first. 如果文件在第二个目录中被重命名,我不希望它在第一个目录中被重命名。 So just one way. 所以只是一种方法。 Now people use File.Move for renaming in the same directory, but that wont work for me, since I dont want the file to be gone from the first directory. 现在人们使用File.Move在同一目录中重命名,但这对我来说不起作用,因为我不希望文件从第一个目录中消失。 So I figured I should use Copy , but the problem is, if it copies the 2nd directory has 2 files. 所以我想应该使用Copy ,但是问题是,如果它复制第二个目录有2个文件。 1 with the old name (since it already existed) + the copy of the file in the first directory. 1(具有旧名称)(因为它已经存在)+文件在第一目录中的副本。 So I figured I have to delete the old file in the second directory, but for some reason this wont work for me. 所以我想我必须删除第二个目录中的旧文件,但是由于某种原因,这对我不起作用。 It wont delete the old file. 它不会删除旧文件。

Here is my code: 这是我的代码:

private void fileSystemWatcher1_Renamed(object sender, RenamedEventArgs e)
{
    String source = ConfigurationManager.AppSettings[@"Directory1"]; // defined this in the app config
    String target = ConfigurationManager.AppSettings[@"Directory2"];
    filepath = Path.Combine(source, e.Name);
    veryoldname = Path.GetFileName(filepath);

    File.Delete(Path.Combine(target, veryoldname));
    File.Copy(filepath, Path.Combine(target, e.Name)); 
}

I was wondering 3 things here. 我想知道这里的三件事。

  1. Is this the best way to rename a file according to a file in a different directory? 这是根据不同目录中的文件重命名文件的最佳方法吗?
  2. If not, how should I do it? 如果没有,我该怎么办?
  3. What am I doing wrong here? 我在这里做错了什么?

Here's the comment discussion rolled into an answer: 这里的评论讨论变成了答案:

Change: 更改:

veryoldname = Path.GetFileName(filepath);

To: 至:

veryoldname = e.OldName;

And change: 并更改:

File.Delete(Path.Combine(target, veryoldname));
File.Copy(filepath, Path.Combine(target, e.Name)); 

To: 至:

File.Move(Path.Combine(target,veryoldname),Path.Combine(target,e.Name));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM