我正在尝试创建一个相册,我想要做的是将图片从其原始路径复制到特定文件夹,然后立即重命名(副本)。
这是我的一段代码(请注意,“ picturedir”是路径):

    string PCname = Environment.UserName;
    Image File;
    OpenFileDialog openfile = new OpenFileDialog();
    openfile.InitialDirectory = @"C:\Users\" + PCname + @"\Pictures";
    if (openfile.ShowDialog() == DialogResult.OK)
    {
       try
       {
           File = Image.FromFile(openfile.FileName);
           pictureBox3.Image = File;

           pictureBox3.Image.Save(picturedir + "\\" + openfile.SafeFileName);
           System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName,
                               picturedir + "\\" + "1");
       }
       catch (Exception ex)
       {
           MessageBox.Show(ex.Message);
       }
    }


如“ try”中的最后一行所示,我想将所选图片重命名为“ 1”。但是,最后一行给出错误“该文件已经存在时无法创建文件”。有任何想法吗?

附注:如果我不使用最后一个“ try”行:System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName, picturedir + "\\" + "1");它会复制所选图片,但显然根本不会重命名。

最佳答案

Here是有关使用文件的文章。

来自文章:

static void Main()
{
    string fileName = "test.txt";
    string sourcePath = @"C:\Users\Public\TestFolder";
    string targetPath =  @"C:\Users\Public\TestFolder\SubDir";

    // Use Path class to manipulate file and directory paths.
    string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
    string destFile = System.IO.Path.Combine(targetPath, fileName);

    // To copy a folder's contents to a new location:
    // Create a new target folder, if necessary.
    if (!System.IO.Directory.Exists(targetPath))
    {
        System.IO.Directory.CreateDirectory(targetPath);
    }

    // To copy a file to another location and
    // overwrite the destination file if it already exists.
    System.IO.File.Copy(sourceFile, destFile, true);
}


如果使用其他文件名,则将获得具有新名称的副本。

关于c# - 重命名图片的副本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52624539/

10-15 17:00