C# 更改C中图像路径的文件名#
我的图像URL如下所示:C# 更改C中图像路径的文件名#,c#,asp.net,string,path,C#,Asp.net,String,Path,我的图像URL如下所示: photo\myFolder\image.jpg photo\myFolder\image-resize.jpg private static string GetFileNameAppendVariation(string fileName, string variation) { string finalPath = Path.GetDirectoryName(fileName); string newfilename = String.Con
photo\myFolder\image.jpg
photo\myFolder\image-resize.jpg
private static string GetFileNameAppendVariation(string fileName, string variation)
{
string finalPath = Path.GetDirectoryName(fileName);
string newfilename = String.Concat(Path.GetFileNameWithoutExtension(fileName), variation, Path.GetExtension(fileName));
return Path.Combine(finalPath, newfilename);
}
我想将其更改为如下所示:
photo\myFolder\image.jpg
photo\myFolder\image-resize.jpg
private static string GetFileNameAppendVariation(string fileName, string variation)
{
string finalPath = Path.GetDirectoryName(fileName);
string newfilename = String.Concat(Path.GetFileNameWithoutExtension(fileName), variation, Path.GetExtension(fileName));
return Path.Combine(finalPath, newfilename);
}
有什么捷径吗?你可以用这个方法
返回不带扩展名的指定路径字符串的文件名
下面是一个.p>或File.Move方法:
System.IO.File.Move(@"photo\myFolder\image.jpg", @"photo\myFolder\image-resize.jpg");
顺便说一句:\是相对路径和/或web路径,请记住。试试这个
File.Copy(Server.MapPath("~/") +"photo/myFolder/image.jpg",Server.MapPath("~/") +"photo/myFolder/image-resize.jpg",true);
File.Delete(Server.MapPath("~/") + "photo/myFolder/image.jpg");
你可以试试这个
string fileName = @"photo\myFolder\image.jpg";
string newFileName = fileName.Substring(0, fileName.LastIndexOf('.')) +
"-resize" + fileName.Substring(fileName.LastIndexOf('.'));
File.Copy(fileName, newFileName);
File.Delete(fileName);
以下代码段更改了文件名,并保持路径和扩展名不变:
string path = @"photo\myFolder\image.jpg";
string newFileName = @"image-resize";
string dir = Path.GetDirectoryName(path);
string ext = Path.GetExtension(path);
path = Path.Combine(dir, newFileName + ext); // @"photo\myFolder\image-resize.jpg"
这是我用来重命名文件的
public static string AppendToFileName(string source, string appendValue)
{
return $"{Path.Combine(Path.GetDirectoryName(source), Path.GetFileNameWithoutExtension(source))}{appendValue}{Path.GetExtension(source)}";
}
我会使用这样的方法:
photo\myFolder\image.jpg
photo\myFolder\image-resize.jpg
private static string GetFileNameAppendVariation(string fileName, string variation)
{
string finalPath = Path.GetDirectoryName(fileName);
string newfilename = String.Concat(Path.GetFileNameWithoutExtension(fileName), variation, Path.GetExtension(fileName));
return Path.Combine(finalPath, newfilename);
}
这样:
string result = GetFileNameAppendVariation(@"photo\myFolder\image.jpg", "-resize");
结果:photo\myFolder\image resize.jpg你的问题没有说太多。为什么String.Replace对你不起作用?@zey你不能使用Find和Replace吗?不,文件类型和文件名可能是动态的:)file.Move会在路径为
images\myFolder\image.jpg的情况下执行最后两行。你的方法还会将路径的图像部分更改为图像大小。我将分别获取目录路径、文件名和扩展名,更改文件名并从所有这些元素重建路径。