一丶删除文件
1 public string DelFile(string fileRelativePath) 2 { 3 4 try 5 { 6 string filePath = Server.MapPath("~" + fileRelativePath); 7 8 //if (System.IO.File.Exists(filePath)) 9 //{ 10 // System.IO.File.Delete(filePath); 11 //} 12 13 FileInfo file = new FileInfo(filePath); 14 if (file.Exists) 15 { 16 file.Delete(); 17 } 18 19 return ""; 20 } 21 catch (Exception) 22 { 23 24 throw; 25 } 26 }
eg1:
try { string item_url = Server.MapPath(FileUrl); FileInfo fileInfo = new FileInfo(item_url); if (fileInfo.Exists) { fileInfo.Delete(); } } catch (Exception) { throw; }
文件流
方法:
public override int Read(byte[] array, int offset, int count);
public override void Write(byte[] array, int offset, int count);
Dispose():释放由 Stream 使用的所有资源
Close()关闭当前流并释放与之关联的所有资源(如套接字和文件句柄)。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; //FileStream类的命名空间 namespace Filestream读写文件 { class Program { static void Main(string[] args) { //FileStream 操作字节的 //1.创建FileStream类对象 FileStream fsread = new FileStream(@"F:C#projectsabc.txt",FileMode.OpenOrCreate,FileAccess.Read); byte[] buffer=new byte[1024*1024*2]; //定义一个2M的字节数组 //返回本次实际读取到的有效字节数 int r=fsread.Read(buffer,0,buffer.Length); //每次读取2M放到字节数组里面 //将字节数组中每一个元素按照指定的编码格式解码成字符串 string s=Encoding.Default.GetString(buffer,0,r); //关闭流 fsread.Close(); //释放流所占用的资源 fsread.Dispose(); Console.WriteLine(s); //打印读取到的内容 Console.ReadKey(); } } }
1. byte[] 和 Stream
/// <summary> /// byte[]转换成Stream /// </summary> /// <param name="bytes"></param> /// <returns></returns> public Stream BytesToStream(byte[] bytes) { Stream stream = new MemoryStream(bytes); return stream; } /// <summary> /// Stream转换成byte[] /// </summary> /// <param name="stream"></param> /// <returns></returns> public byte[] StreamToBytes(Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); stream.Seek(0, SeekOrigin.Begin); // 设置当前流的位置为流的开始 return bytes; }
2.文件 和 Stream
/// <summary> /// 从文件读取Stream /// </summary> /// <param name="path"></param> /// <returns></returns> public Stream FileToStream(string path) { FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); // 打开文件 byte[] bytes = new byte[fileStream.Length]; // 读取文件的byte[] fileStream.Read(bytes, 0, bytes.Length); fileStream.Close(); Stream stream = new MemoryStream(bytes); // 把byte[]转换成Stream return stream; } /// <summary> /// 将Stream写入文件 /// </summary> /// <param name="stream"></param> /// <param name="path"></param> public void StreamToFile(Stream stream, string path) { byte[] bytes = new byte[stream.Length]; // 把Stream转换成byte[] stream.Read(bytes, 0, bytes.Length); stream.Seek(0, SeekOrigin.Begin); // 设置当前流的位置为流的开始 FileStream fs = new FileStream(path, FileMode.Create); // 把byte[]写入文件 BinaryWriter bw = new BinaryWriter(fs); bw.Write(bytes); bw.Close(); fs.Close(); }