public string SaveFile(byte[] binData, string filePath, string fileName, int type, string fileType)
{
///定义并实例化一个内存流,以存放提交上来的字节数组。
MemoryStream m = new MemoryStream(binData);
FileStream fileStream = null;
try
{
string savePath = System.Configuration.ConfigurationSettings.AppSettings["DcFilePath"];
//不是绝对路径
if (savePath.IndexOf(":\\") < 0) savePath = Server.MapPath(savePath);
//没有反斜杠
if (!savePath.EndsWith("\\")) savePath += "\\";
//目录
savePath += filePath;
//没有文件夹,创建文件夹
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
if (type == 0)
{
fileName = "\\" + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
}
if (!File.Exists(savePath + fileName + fileType))
{
fileName = "\\" + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
}
fileName = fileName + fileType;
//写文件
fileStream = new FileStream(savePath + fileName, FileMode.Create);
m.WriteTo(fileStream);
StreamWriter sw=new StreamWriter(savePath+".txt");
sw.WriteLine(binData.Length.ToString());
sw.Close();
return "filePath.Replace("\\", "/") + fileName.Replace("\\", "/");
}
catch
{
return "上传文件出错|1";
}
finally
{
m.Close();
fileStream.Close();
}
}
有时候下面的函数会报错,也不知道什么原因. 还是用上传控件自带的转换.
#region 将文件转化成2进制流 ConvertFileStreamToByteBuffer
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public byte[] getBinaryFile(string filename)
{
if (File.Exists(filename))
{
FileStream s = null;
try
{
//打开现有文件以进行读取。
s = File.OpenRead(filename);
return this.ConvertStreamToByteBuffer(s);
}
catch
{
return new byte[0];
}
finally
{
s.Close();
}
}
else
{
return new byte[0];
}
}
#endregion
#region 将流文件转化成2进制字节数组Convert FileStream Into Byte
/// </summary>
/// <param name="theStream"></param>
/// <returns></returns>
public byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)
{
int b1;
MemoryStream tempStream = new System.IO.MemoryStream();
try
{
while ((b1 = theStream.ReadByte()) != -1)
{
tempStream.WriteByte(((byte)b1));
}
return tempStream.ToArray();
}
catch
{
return new byte[0];
}
finally
{
tempStream.Close();
}
}
#endregion