您的位置:首页 > 编程语言 > C#

C# Winform 上传本地文件到服务器路径

2011-09-03 17:48 666 查看
/// <summary>

/// 判断是否以奇数个引号开始

/// </summary>

/// <param name="dataCell"></param>

/// <returns></returns>

private bool IfOddStartQuota(string dataCell)

{

int quotaCount;

bool oddQuota;

quotaCount = 0;

for (int i = 0; i < dataCell.Length; i++)

{

if (dataCell[i] == '/"')

{

quotaCount++;

}

else

{

break;

}

}

oddQuota = false;

if (quotaCount % 2 == 1)

{

oddQuota = true;

}

return oddQuota;

}

/// <summary>

/// 判断是否以奇数个引号结尾

/// </summary>

/// <param name="dataCell"></param>

/// <returns></returns>

private bool IfOddEndQuota(string dataCell)

{

int quotaCount;

bool oddQuota;

quotaCount = 0;

for (int i = dataCell.Length - 1; i >= 0; i--)

{

if (dataCell[i] == '/"')

{

quotaCount++;

}

else

{

break;

}

}

oddQuota = false;

if (quotaCount % 2 == 1)

{

oddQuota = true;

}

return oddQuota;

}

/// <summary>

/// 加入新的数据行

/// </summary>

/// <param name="newDataLine">新的数据行</param>

private void AddNewDataLine(string newDataLine)

{

//Debug.WriteLine("NewLine:" + newDataLine);

//return;

ArrayList colAL = new ArrayList();

string[] dataArray = newDataLine.Split(',');

bool oddStartQuota; //是否以奇数个引号开始

string cellData;

oddStartQuota = false;

cellData = "";

for (int i = 0; i < dataArray.Length; i++)

{

if (oddStartQuota)

{

//因为前面用逗号分割,所以要加上逗号

cellData += "," + dataArray[i];

//是否以奇数个引号结尾

if (IfOddEndQuota(dataArray[i]))

{

colAL.Add(GetHandleData(cellData));

oddStartQuota = false;

continue;

}

}

else

{

//是否以奇数个引号开始

if (IfOddStartQuota(dataArray[i]))

{

//是否以奇数个引号结尾,不能是一个双引号,并且不是奇数个引号

if (IfOddEndQuota(dataArray[i]) && dataArray[i].Length > 2 && !IfOddQuota(dataArray[i]))

{

colAL.Add(GetHandleData(dataArray[i]));

oddStartQuota = false;

continue;

}

else

{

oddStartQuota = true;

cellData = dataArray[i];

continue;

}

}

else

{

colAL.Add(GetHandleData(dataArray[i]));

}

}

}

if (oddStartQuota)

{

throw new Exception("数据格式有问题");

}

this.rowAL.Add(colAL);

}

/// <summary>

/// 去掉格子的首尾引号,把双引号变成单引号

/// </summary>

/// <param name="fileCellData"></param>

/// <returns></returns>

private string GetHandleData(string fileCellData)

{

if (fileCellData == "")

{

return "";

}

if (IfOddStartQuota(fileCellData))

{

if (IfOddEndQuota(fileCellData))

{

return fileCellData.Substring(1, fileCellData.Length - 2).Replace("/"/"", "/""); //去掉首尾引号,然后把双引号变成单引号

}

else

{

throw new Exception("数据引号无法匹配" + fileCellData);

}

}

else

{

//考虑形如"" """" """"""

if (fileCellData.Length > 2 && fileCellData[0] == '/"')

{

fileCellData = fileCellData.Substring(1, fileCellData.Length - 2).Replace("/"/"", "/""); //去掉首尾引号,然后把双引号变成单引号

}

}

return fileCellData;

}

}

#region write csv类说明信息

/// <summary>

/// <DL>

/// <DT><b>写CSV文件类,首先给CSV文件赋值,最后通过Save方法进行保存操作</b></DT>

/// <DD>

/// <UL>

/// </UL>

/// </DD>

/// </DL>

/// <Author>yangzhihong</Author>

/// <CreateDate>2006/01/16</CreateDate>

/// <Company></Company>

/// <Version>1.0</Version>

/// </summary>

#endregion

public class CsvStreamWriter

{

private ArrayList rowAL; //行链表,CSV文件的每一行就是一个链

private string fileName; //文件名

private Encoding encoding; //编码

public CsvStreamWriter()

{

this.rowAL = new ArrayList();

this.fileName = "";

this.encoding = Encoding.Default;

}

/// <summary>

///

/// </summary>

/// <param name="fileName">文件名,包括文件路径</param>

public CsvStreamWriter(string fileName)

{

this.rowAL = new ArrayList();

this.fileName = fileName;

this.encoding = Encoding.Default;

}

/// <summary>

///

/// </summary>

/// <param name="fileName">文件名,包括文件路径</param>

/// <param name="encoding">文件编码</param>

public CsvStreamWriter(string fileName, Encoding encoding)

{

this.rowAL = new ArrayList();

this.fileName = fileName;

this.encoding = encoding;

}

/// <summary>

/// row:行,row = 1代表第一行

/// col:列,col = 1代表第一列

/// </summary>

public string this[int row, int col]

{

set

{

//对行进行判断

if (row <= 0)

{

throw new Exception("行数不能小于0");

}

else if (row > this.rowAL.Count) //如果当前列链的行数不够,要补齐

{

for (int i = this.rowAL.Count + 1; i <= row; i++)

{

this.rowAL.Add(new ArrayList());

}

}

else

{

}

//对列进行判断

if (col <= 0)

{

throw new Exception("列数不能小于0");

}

else

{

ArrayList colTempAL = (ArrayList)this.rowAL[row - 1];

//扩大长度

if (col > colTempAL.Count)

{

for (int i = colTempAL.Count; i <= col; i++)

{

colTempAL.Add("");

}

}

this.rowAL[row - 1] = colTempAL;

}

//赋值

ArrayList colAL = (ArrayList)this.rowAL[row - 1];

colAL[col - 1] = value;

this.rowAL[row - 1] = colAL;

}

}

/// <summary>

/// 文件名,包括文件路径

/// </summary>

public string FileName

{

set

{

this.fileName = value;

}

}

/// <summary>

/// 文件编码

/// </summary>

public Encoding FileEncoding

{

set

{

this.encoding = value;

}

}

/// <summary>

/// 获取当前最大行

/// </summary>

public int CurMaxRow

{

get

{

return this.rowAL.Count;

}

}

/// <summary>

/// 获取最大列

/// </summary>

public int CurMaxCol

{

get

{

int maxCol;

maxCol = 0;

for (int i = 0; i < this.rowAL.Count; i++)

{

ArrayList colAL = (ArrayList)this.rowAL[i];

maxCol = (maxCol > colAL.Count) ? maxCol : colAL.Count;

}

return maxCol;

}

}

/// <summary>

/// 添加表数据到CSV文件中

/// </summary>

/// <param name="dataDT">表数据</param>

/// <param name="beginCol">从第几列开始,beginCol = 1代表第一列</param>

public void AddData(DataTable dataDT, int beginCol)

{

if (dataDT == null)

{

throw new Exception("需要添加的表数据为空");

}

int curMaxRow;

curMaxRow = this.rowAL.Count;

for (int i = 0; i < dataDT.Rows.Count; i++)

{

for (int j = 0; j < dataDT.Columns.Count; j++)

{

this[curMaxRow + i + 1, beginCol + j] = dataDT.Rows[i][j].ToString();

}

}

}

/// <summary>

/// 保存数据,如果当前硬盘中已经存在文件名一样的文件,将会覆盖

/// </summary>

public void Save()

{

//对数据的有效性进行判断

if (this.fileName == null)

{

throw new Exception("缺少文件名");

}

else if (File.Exists(this.fileName))

{

File.Delete(this.fileName);

}

if (this.encoding == null)

{

this.encoding = Encoding.Default;

}

System.IO.StreamWriter sw = new StreamWriter(this.fileName, false, this.encoding);

for (int i = 0; i < this.rowAL.Count; i++)

{

sw.WriteLine(ConvertToSaveLine((ArrayList)this.rowAL[i]));

}

sw.Close();

}

public void Save(string Url, string FileName)

{

if (Url != String.Empty && FileName != String.Empty)

{

System.Net.WebClient webclient = new System.Net.WebClient();

webclient.UploadFile(Url, this.fileName);

}

}

/**//**//**//// <summary>

/// WebClient上传文件至服务器

/// </summary>

/// <param name="localFilePath">文件名,全路径格式</param>

/// <param name="serverFolder">服务器文件夹路径</param>

/// <param name="reName">是否需要修改文件名,这里默认是日期格式</param>

/// <returns></returns>

public bool UploadFile(string localFilePath, string serverFolder,bool reName)

{

bool upload = false;

string fileNameExt, newFileName, uriString;

if (reName)

{

fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf(".") + 1);

newFileName = " LCZ2KYZ DELIVERY (" + DateTime.Now.ToString("yyyy-MM-dd-HHmmss") + ")" + fileNameExt;

}

else

{

newFileName = localFilePath.Substring(localFilePath.LastIndexOf("//")+1);

}

if (!serverFolder.EndsWith("/") && !serverFolder.EndsWith(""))

{

serverFolder = serverFolder + "/";

}

uriString = serverFolder + newFileName; //服务器保存路径

/**//**//**//// 创建WebClient实例

WebClient myWebClient = new WebClient();

myWebClient.Credentials = CredentialCache.DefaultCredentials;

// 要上传的文件

FileStream fs = new FileStream(localFilePath, FileMode.Open, FileAccess.Read);

BinaryReader r = new BinaryReader(fs);

try

{

//使用UploadFile方法可以用下面的格式

//myWebClient.UploadFile(uriString,"PUT",localFilePath);

byte[] postArray = r.ReadBytes((int)fs.Length);

Stream postStream = myWebClient.OpenWrite(uriString, "PUT");

if (postStream.CanWrite)

{

postStream.Write(postArray, 0, postArray.Length);

upload = true;

}

else

{

upload = false;

//MessageBox.Show("文件目前不可写!");

BLLMail.SendMailLocalhost("Upload local File to remote path failed", uriString + "文件目前不可写!");

}

postStream.Close();

}

catch

{

upload = false;

//MessageBox.Show("文件上传失败,请稍候重试~");

BLLMail.SendMailLocalhost("Upload local File to remote path failed", uriString + "文件上传失败,请检查");

}

return upload;

}

/**//**//**//// <summary>

/// 下载服务器文件至客户端

/// </summary>

/// <param name="uri">被下载的文件地址</param>

/// <param name="savePath">另存放的目录</param>

public bool Download(string uri, string savePath)

{

string fileName; //被下载的文件名

if (uri.IndexOf("") > -1)

{

fileName = uri.Substring(uri.LastIndexOf("") + 1);

}

else

{

fileName = uri.Substring(uri.LastIndexOf("/") + 1);

}

if (!savePath.EndsWith("/") && !savePath.EndsWith(""))

{

savePath = savePath + "/";

}

savePath += fileName; //另存为的绝对路径+文件名

WebClient client = new WebClient();

try

{

client.DownloadFile(uri, savePath);

}

catch

{

return false;

}

return true;

}

/// <summary>

/// 保存数据,如果当前硬盘中已经存在文件名一样的文件,将会覆盖

/// </summary>

/// <param name="fileName">文件名,包括文件路径</param>

public void Save(string fileName)

{

this.fileName = fileName;

Save();

}

/// <summary>

/// 保存数据,如果当前硬盘中已经存在文件名一样的文件,将会覆盖

/// </summary>

/// <param name="fileName">文件名,包括文件路径</param>

/// <param name="encoding">文件编码</param>

public void Save(string fileName, Encoding encoding)

{

this.fileName = fileName;

this.encoding = encoding;

Save();

}

/// <summary>

/// 转换成保存行

/// </summary>

/// <param name="colAL">一行</param>

/// <returns></returns>

private string ConvertToSaveLine(ArrayList colAL)

{

string saveLine;

saveLine = "";

for (int i = 0; i < colAL.Count; i++)

{

saveLine += ConvertToSaveCell(colAL[i].ToString());

//格子间以逗号分割

if (i < colAL.Count - 1)

{

saveLine += ",";

}

}

return saveLine;

}

/// <summary>

/// 字符串转换成CSV中的格子

/// 双引号转换成两个双引号,然后首尾各加一个双引号

/// 这样就不需要考虑逗号及换行的问题

/// </summary>

/// <param name="cell">格子内容</param>

/// <returns></returns>

private string ConvertToSaveCell(string cell)

{

cell = cell.Replace("/"", "/"/"");

return "/"" + cell + "/"";

}

}

}

调用方法:

CsvStreamWriter csw = new CsvStreamWriter(FileName, Encoding.UTF8);

// csw.AddData(dtSHIP, 1);

//csw.Save();

if (csw.UploadFile(FileName, SHIPFILEPATHREMOTE, false))

{

MessageBox.Show("Shipping數據上传成功");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: