2

私は c# を使用して WinForm アプリケーションに取り組んでいます。ボタンを使用して画像ファイル (.jpeg または .bmp) を参照しています。ユーザーがファイルを参照して [OK] をクリックし、別の [続行または更新] ボタンをクリックすると、参照したファイルの名前を変更して、すべての画像ファイルがデフォルトで保存される事前定義されたディレクトリに保存する必要があります。交流!

どうすればこれを達成できますか?ファイルの参照に 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);
}

Copy メソッドの詳細。

于 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 Image.png
B.png 画像 (1).png
C.png 画像 (2).png
于 2012-10-15T10:58:50.910 に答える
0

File.Copy() メソッドでそれを行うことができます。定義済みのディレクトリと新しいファイル名を宛先パラメーターとして指定するだけです。

詳細については、こちらをご覧ください

于 2012-10-15T10:47:23.947 に答える