获取文件全路径、目录、扩展名、文件名称:
1 using System; 2 using System.IO; 3 4 class Program 5 { 6 static void Main(string[] args) 7 { 8 9 //获取当前运行程序的目录 10 string fileDir = Environment.CurrentDirectory; 11 Console.WriteLine("当前程序目录:" + fileDir); 12 13 //一个文件目录 14 string filePath = "C:\\JiYF\\BenXH\\BenXHCMS.xml"; 15 Console.WriteLine("该文件的目录:" + filePath); 16 17 string str = "获取文件的全路径:" + Path.GetFullPath(filePath); //-->C:\JiYF\BenXH\BenXHCMS.xml 18 Console.WriteLine(str); 19 str = "获取文件所在的目录:" + Path.GetDirectoryName(filePath); //-->C:\JiYF\BenXH 20 Console.WriteLine(str); 21 str = "获取文件的名称含有后缀:" + Path.GetFileName(filePath); //-->BenXHCMS.xml 22 Console.WriteLine(str); 23 str = "获取文件的名称没有后缀:" + Path.GetFileNameWithoutExtension(filePath); //-->BenXHCMS 24 Console.WriteLine(str); 25 str = "获取路径的后缀扩展名称:" + Path.GetExtension(filePath); //-->.xml 26 Console.WriteLine(str); 27 str = "获取路径的根目录:" + Path.GetPathRoot(filePath); //-->C:\ 28 Console.WriteLine(str); 29 Console.ReadKey(); 30 } 31 }
Image.FromFile 一旦使用后,对应的文件在一直调用其生成的Image对象被Disponse前都不会被解除锁定,这就造成了一个问题,就是在这个图形被解锁前无法对图像进行操作(比如删除,修改等操作).
在以前用的过程中曾用过下面三个方法解决问题.
第一种方法,在要进行文件操作前将Image对象销毁.
PictureBox picbox;
if(picbox.Image!=null)picbox.Image.Disponse();
第二种方法,就是在加载图像的时候用一种方法替代:
System.Drawing.Image img = System.Drawing.Image.FromFile(filepath);
System.Drawing.Image bmp = new System.Drawing.Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
g.DrawImage(img, 0, 0);
g.Flush();
g.Dispose();
img.Dispose();
//下面开始使用bmp作为显示的Image对象
System.Drawing.Image img = System.Drawing.Image.FromFile(filepath);
System.Drawing.Image bmp = new System.Drawing.Bitmap(img);
img.Dispose();
方法四:
fs = New System.IO.FileStream("C:\WINNT\Web\Wallpaper\Fly Away.jpg",
IO.FileMode.Open, IO.FileAccess.Read)
PictureBox1.Image = System.Drawing.Image.FromStream(fs)
fs.Close()
Image类的FromFile方法打开文件と后没有关闭,导致文件锁定,无法进行删除、移动等操作。
该而使用FromStream方法,代码如下:
//读取文件流
FileStream fileStream = new FileStream(iconPath, FileMode.Open, FileAccess.Read);
int byteLength = (int)fileStream.Length;
byte[] fileBytes = new byte[byteLength];
fileStream.Read(fileBytes, 0, byteLength);
//文件流关閉,文件解除锁定
fileStream.Close();
Pictrue.Image = Image.FromStream(new MemoryStream(fileBytes));
因为FromStream方法参数应用的流必须一直保持打开,故代码中有一个文件流向MemeoryStream流的转换,从而可以关闭文件流,保持MemoryStream流的打开状态。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具