Binary Upload / Download With Webservice

Binary Upload / Download With Webservice

Upload:

Client

List<byte[]> byteFileList = new List<byte[]>();
byteFileList.Add(byteFile);
List<string> fileNameList = new List<string>();
fileNameList.Add(...);
string result = UploadFile(byteFileList.ToArray(),  fileNameList.ToArray()); //UploadFile 為 WebService

Server

public string UploadFile(byte[][] byteFile, string[] fileName)
{
    string result = string.Empty;
    string path = "path...";

    if (!File.Exists(path))
        System.IO.Directory.CreateDirectory(path);

    string pathTemp = path;
    MemoryStream memoryStream;
    FileStream fileStream;
    try
    {
        for (int i = 0; i < fileName.Length; i++)
        {
            path += fileName[i];
            memoryStream = new MemoryStream(byteFile[i]);
            fileStream = new FileStream(path, FileMode.Create);
            memoryStream.WriteTo(fileStream);
            memoryStream.Flush();
            memoryStream.Close();
            fileStream.Flush(); 
            fileStream.Close();
            fileStream = null; 
            memoryStream = null;

            if (File.Exists(path)) //驗證檔案是否成功新增
                result += fileName[i] + ", ";

        }

        return "success, " + result;

    }
    catch (Exception ex)
    {
        return "error, " + result;
    }
}

Download:

Client

string fileName = "abc.xlsm";
try
{   SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
    saveFileDialog.FileName = fileName;
    saveFileDialog.Filter = "Excel(*.xlsx) 檔案|*.xlsx|Excel(*.xls) 檔案|*.xls"; / 以 Excel 為例
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        byte[] data = DownloadFile(fileName, @"SourcePath", out meg); //DownloadFile 為 WevService

        MemoryStream memoryStream = new MemoryStream(data);
        FileStream fileStream = new FileStream(saveFileDialog.FileName, FileMode.Create);
        memoryStream.WriteTo(fileStream);
        memoryStream.Flush(); 
        memoryStream.Close();
        fileStream.Flush(); 
        fileStream.Close();
        fileStream = null;
        memoryStream = null;
    }
}
catch (Exception ex)
{

}

Server

public byte[] DownloadFile(string fileName, string filePath, out string meg)
{
    string path = filePath + fileName;
    try
    {
        if (File.Exists(path))
        {
            meg = "1, " + path;
            return File.ReadAllBytes(path);
        }
        else
            meg = "2, 檔案不存在!";
    }
    catch (Exception ex)
    {
        meg = "-1, " + ex.Message.ToString();
        return null;
    } 
    return null;
}