C# 文件移动

发布时间 2023-07-04 10:51:19作者: 一介桃白白

 

将文件从文件夹A移动到文件夹B并按规则重命名

// <summary>
    /// 将文件移动到指定目录
    /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
    /// <param name="descDirectoryPath">移动到的目录的路径</param>
    /// <param name="newFileName">移动到的目录后的新文件名</param>
    ///</summary>

    public static string Move(string sourceFilePath, string descDirectoryPath,string newFileName)
    {
        //获取源文件的扩展名
        string sourceExtFileName = Path.GetExtension(sourceFilePath);

        if (!Directory.Exists(descDirectoryPath))
        {
            Directory.CreateDirectory(descDirectoryPath);
            //如果目标中存在同名文件,则删除
            
        }
        if (File.Exists(descDirectoryPath + "\\" + newFileName + sourceExtFileName))
        {
            File.Delete(descDirectoryPath + "\\" + newFileName + sourceExtFileName);
        }
        //将文件移动到指定目录
        string newFilePath = descDirectoryPath + "\\" + newFileName + sourceExtFileName;
        File.Move(sourceFilePath, newFilePath);
        return newFilePath;
    }

搭配使用_生成6位随机数字

Random random = new Random();
            int randomNumber = random.Next(1, 10) * 100000 + random.Next(0, 100000);
            string code = randomNumber.ToString("D6");