C#实现图片上传小功能 支持市面上大部分格式的照片上传

文章描述了一个C#方法,通过OpenFileDialog选择图片文件,检查目标文件夹并进行重命名或直接复制,确保文件不重复。方法还包括生成唯一文件名的功能。
/// <summary>
/// 新加图片的保存路径
/// </summary>
private string targetFilePath1;
/// <summary>
/// 已有图片新的保存路径
/// </summary>
private string targetFolderPath1;
private string newFileName = null;
public void FileImage()
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Filter = "所有图像文件 (*.BMP, *.JPG, *.GIF, *.PNG, *.JPEG, *.PNG, *.TIFF, *.TIF, *.ICO, *.CUR, *.SVG, *.WEBP, *.JP2,*.PSD,*.PDF)|*.BMP; *.JPG; *.GIF; *.PNG; *.JPEG; *.TIFF; *.TIF; *.ICO; *.CUR; *.SVG; *.WEBP; *.JP2;*.PSD; *.PDF)";
    openFileDialog1.FilterIndex = 1;

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string selectedFilePath1 = openFileDialog1.FileName;
        targetFolderPath1 = "./drinkimg/"; // 指定目标文件夹路径  
        targetFilePath1 = Path.Combine(targetFolderPath1, Path.GetFileName(selectedFilePath1));

        // 检查目标文件夹是否存在,如果不存在则创建  
        if (!Directory.Exists(targetFolderPath1))
        {
            Directory.CreateDirectory(targetFolderPath1);
        }
        // 检查目标文件夹中是否存在正在上传的照片
        if (File.Exists(targetFilePath1))
        {
            // 生成一个新的文件名
            string uniqueFileName = GenerateUniqueFileName(targetFilePath1);
            string fileExtension = Path.GetExtension(targetFilePath1);
            newFileName = Path.Combine(targetFolderPath1, $"{uniqueFileName}{fileExtension}");
            // 复制图片文件并使用新文件名保存到目标文件夹  
            File.Copy(selectedFilePath1, newFileName);

            // 在这里可以添加额外的逻辑,比如显示成功消息等  
            MessageBox.Show($"上传成功!新文件名为: {Path.GetFileName(newFileName)}");
        }
        else
        {
            // 复制图片文件到目标文件夹  
            File.Copy(selectedFilePath1, targetFilePath1);
            // 在这里可以添加额外的逻辑,比如显示成功消息等  
            MessageBox.Show($"上传成功!文件名为: {Path.GetFileName(targetFilePath1)}");
        }
    }
}
#region 新文件名函数
string GenerateUniqueFileName(string filePath)
{
    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
    string fileExtension = Path.GetExtension(filePath);
    string newFileName = fileNameWithoutExtension;
    int count = 1;

    while (File.Exists(Path.Combine(targetFolderPath1, $"{newFileName}{fileExtension}")))
    {
        newFileName = $"{fileNameWithoutExtension}_{count}";
        count++;
    }

    return newFileName;
}
#endregion

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lucky.帅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值