1、二进制转文件操作。
首先调用
//你的文件
byte[] data = null;
//路径
string filePath = System.AppDomain.CurrentDomain.BaseDirectory + @"\\Uploads\\";
string errMsg = string.Empty;
string guid = Guid.NewGuid().ToString();
UploadFile(data, filePath, guid + ".xml", ref errMsg);
函数实现
/// <summary>
/// 文件
/// </summary>
/// <param name="fs">二进制流</param>
/// <param name="vitualPath">路径</param>
/// <param name="fileName">文件名</param>
/// <param name="msg">错误信息</param>
/// <returns></returns>
private bool UploadFile(byte[] fs, string vitualPath, string fileName, ref string msg)
{
string filepath;
if (!System.IO.Directory.Exists(vitualPath))
{
System.IO.Directory.CreateDirectory(vitualPath);
}
if (vitualPath.EndsWith("\\"))
{
filepath = vitualPath + fileName;
}
else
filepath = vitualPath + "\\" + fileName;
try
{
///定义并实例化一个内存流,以存放提交上来的字节数组。
System.IO.MemoryStream m = new System.IO.MemoryStream(fs);
///定义实际文件对象,保存上载的文件。
//FileStream f = new FileStream(Server.MapPath("./") + "\\"
// + FileName, FileMode.Create);
System.IO.FileStream f = new System.IO.FileStream(filepath, System.IO.FileMode.Create);
///把内内存里的数据写入物理文件
m.WriteTo(f);
m.Close();
f.Close();
f = null;
m = null;
msg = "";
return true;
}
catch (Exception ex)
{
msg = ex.Message;
return false;
}
}
2、删除文件操作。
首先调用
//文件夹路径及名字
DeleteFile(filePath + "/" + guid + ".txt");
函数实现
/// <summary>
/// 删除指定文件
/// </summary>
/// <param name="filePath"></param>
private void DeleteFile(string filePath)
{
if (System.IO.File.Exists(filePath))
{
try
{
System.IO.File.Delete(filePath);
}
catch
{ }
}
}