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

本文详细介绍了从远程服务器下载文件并将其保存到本地的过程。包括获取文件流、检查目标路径的有效性、创建必要目录以及使用FileStream将数据写入磁盘等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值