我正在尝试创建相册,我想要做的是将图片从其原始路径复制到特定文件夹,然后立即重命名(副本)。 这是我的一段代码(请注意,“ 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”。但是,最后一行给出错误“该文件已经存在时无法创建文件”。有什么想法吗?
P.S .:如果我不使用最后的“ try”行:System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName, picturedir + "\\" + "1");
会复制所选的图片,但显然根本不会重命名。
答案 0 :(得分:3)
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);
}
如果使用其他文件名,则将获得新名称的副本。