⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 filesave.cs

📁 WCF文件传输示例
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.Text;
using FileInterface;
using System.Windows.Forms;
using System.ServiceModel;
using System.IO;
using System.Threading;
using FileService;

namespace FileService2
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] 
    class FileSave : IFileInterface
    {
        public void UploadFile(FileUploadMessage request)
        {
            string id = OperationContext.Current.SessionId;

            string logInfo;

            Program.Get_ILog().Log(logInfo = string.Format("开始接收文件 name={0},path={1},threadid={2}",
                Thread.CurrentThread.GetHashCode(),
                request.FileName, request.SavePath));

            string uploadFolder = AppValue.GetParam()._saveDir; 
            string savaPath = request.SavePath;
            string fileName = request.FileName;
            Stream sourceStream = request.FileData;
            FileStream targetStream = null;
           
            if (!sourceStream.CanRead)
            {
                throw new Exception("数据流不可读!");
            }
            if (savaPath == null) savaPath = @"default\";
            if (!savaPath.EndsWith("\\")) savaPath += "\\";
            if (!uploadFolder.EndsWith("\\")) uploadFolder += "\\";

            uploadFolder = uploadFolder + savaPath;
            if (!Directory.Exists(uploadFolder))
            {
                Directory.CreateDirectory(uploadFolder);
            }

            int fileSize = 0;
            string filePath = Path.Combine(uploadFolder, fileName);
            try
            {
                using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    //read from the input stream in 4K chunks
                    //and save to output stream
                    const int bufferLen = 4096;
                    byte[] buffer = new byte[bufferLen];
                    int count = 0;

                    while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
                    {
                        targetStream.Write(buffer, 0, count);
                        fileSize += count;
                        //Thread.Sleep(2000);
                    }
                    targetStream.Close();
                    sourceStream.Close();
                }
            }
            catch(Exception ex)
            {
                Program.Get_ILog().Log(logInfo+ex.Message);
            }

            Program.Get_ILog().Log(string.Format("接收文件完毕 name={0},path={1},filesize={2}",
              request.FileName, request.SavePath, fileSize));
        }

        public void Test(string msg)
        {
            MessageBox.Show(msg);
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -