C# 读取Stream流文件并保存到本地

Stream stream = fileBLL.DownloadFile(fileInfo); //获取文件流
byte[] srcBuf = new Byte[stream.Length];
stream.Read(srcBuf, 0, srcBuf.Length);
stream.Seek(0, SeekOrigin.Begin);  

//判断路径是否正确
if (string.IsNullOrEmpty(filePath))
{
    return false;
}
else
{
    try //确保目录存在
    {
        if (string.IsNullOrEmpty(folderPath))
        {
                return false;
        }
        if (Directory.Exists(folderPath))
        {
                return true;
        }
        else
        {
            try
            {
                return Directory.CreateDirectory(folderPath) != null;
            }
            catch(Exception ex)
            {
                Debug.WriteLine("创建文件夹失败:" + ex.Message);
                return false;
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine("生成文件信息对象失败:" + ex.Message);
        return false;
    }
}

//保存文件到本地
try
{
    using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
    {
        fs.Write(buf, 0, buf.Length);
        fs.Close();
    }

    return true;
}
catch (Exception ex)
{
    Debug.WriteLine(string.Format("写入文件出错:消息={0},堆栈={1}", ex.Message, ex.StackTrace));
    return false;
}

 

你可能感兴趣的:(C#)