2

我正在使用 c# 开发 WinForm 应用程序。我正在使用一个按钮来浏览图像文件(.jpeg 或 .bmp)。当用户浏览文件并单击确定时,单击另一个“继续或更新”按钮时,我希望浏览的文件应重命名并保存到默认情况下将保存所有图像文件的预定义目录,无需太多用户相互作用!

我怎样才能做到这一点?我使用 openFileDialog 浏览文件,但不知道还能做什么。

4

3 回答 3

5
//detination filename
string newFileName = @"C:\NewImages\NewFileName.jpg";    

// if the user presses OK instead of Cancel
if (openFileDialog1.ShowDialog() == DialogResult.OK) 
{
    //get the selected filename
    string filename = openFileDialog1.FileName; 

    //copy the file to the new filename location and overwrite if it already exists 
    //(set last parameter to false if you don't want to overwrite)
    System.IO.File.Copy(filename, newFileName, true);
}

有关复制方法的更多信息。

于 2012-10-15T10:50:51.820 回答
1

首先,您必须实现一个可以生成唯一文件名的复制功能:

private void CopyWithUniqueName(string source, 
                                string targetPath,
                                string targetFileName)
{
    string fileName = Path.GetFileNameWithoutExtension(targetFileName);
    string extension = Path.GetExtension(targetFileName);

    string target = File.Exists(Path.Combine(targetPath, targetFileName);
    for (int i=1; File.Exists(target); ++i)
    {
        target = Path.Combine(targetPath, String.Format("{0} ({1}){2}",
            targetFileName, i, extension));
    }

    File.Copy(source, target);
}

然后你就可以使用它了,假设defaultTargetPath是复制图像的默认目标文件,并且defaultFileName是图像的默认文件名:

void button1_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() != DialogResult.OK)
        return;

    CopyWithUniqueName(openFileDialog1.FileName, 
        defaultTargetPath, defaultFileName);
}

多选时:

foreach (string fileName in openFileDialog1.FileNames)
{
    CopyWithUniqueName(fileName, 
        defaultTargetPath, defaultFileName);
}

你会得到这个(假设defaultFileName是“Image.png”):

源目标
A.png 图片.png
B.png 图片 (1).png
C.png 图片 (2).png
于 2012-10-15T10:58:50.910 回答
0

您可以使用 File.Copy() 方法来做到这一点。只需将预定义的目录和新文件名作为目标参数。

有关更多信息,请参见此处

于 2012-10-15T10:47:23.947 回答