/// <summary>
/// 下载并更新文件(本地客户端存在文件就用服务器文件覆盖掉,不存在该文件就创建并写入)
/// </summary>
/// <param name="serverFullName">服务器文件全名</param>
/// <param name="localFullName">本地文件全名</param>
/// <returns></returns>
private bool DownUpdateFile(string serverFullName, string localFullName, string FolderName, out string mes)
{
try
{
int num = 0;
num++;
string url = txtdaml.Text.Trim();
/// 创建WebClient实例
WebClient myWebClient = new WebClient();
//NetworkCredential nc = new NetworkCredential(ServerUserName, ServerPassWord);
Uri addy = new Uri(serverFullName);
myWebClient.Credentials = CredentialCache.DefaultCredentials; ;
string[] arrayfile = Directory.GetFiles(txtdaml.Text);
WebRequest webReq = WebRequest.Create(localFullName);
WebResponse webRes = webReq.GetResponse();
long fileLength = webRes.ContentLength;
string fileName = Path.GetFileName(localFullName);
//this.label4.Text = String.Format(
// CultureInfo.InvariantCulture,
// "上传进度 {0}/{1}",
// num,
// arrayfile.Length,
// );
//rchtxtInfo.Text = rchtxtInfo.Text + string.Format("上传文件成功:{0},文件大小:{1}KB\n", fileName, (fileLength / 1024.0).ToString("N2")) + "\r\n";
progressBar1.Maximum = (int)fileLength;
progressBar1.Value = 0;
Application.DoEvents();
Stream stream = webRes.GetResponseStream();
StreamReader sr = new StreamReader(stream);
byte[] bufferbyte = new byte[fileLength];
int allByte = (int)bufferbyte.Length;
int startByte = 0;
while (fileLength > 0)
{
int downByte = stream.Read(bufferbyte, startByte, allByte);
if (downByte == 0)
{
break;
}
startByte = startByte + downByte;
allByte = allByte - downByte;
progressBar1.Value = startByte;
//即progressBar1.Value = progressBar1.Value + downByte;
}
//本地文件存在则覆盖,不存在则创建
//string localFile = fbd.SelectedPath + "\\" + list[i];
//CreateNewDiretory(localFullName);
try
{
myWebClient.UploadFile(addy, localFullName);
//rchtxtInfo.Text = rchtxtInfo.Text + string.Format("上传文件成功:{0}\n", FolderName + "\\" + fileName) + "\r\n";
}
catch
{
//创建或更新覆盖文件
FileStream fs = new FileStream(serverFullName, FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(bufferbyte, 0, bufferbyte.Length);
stream.Close();
sr.Close();
fs.Close();
//rchtxtInfo.Text = rchtxtInfo.Text + string.Format("上传文件成功:{0}\n", FolderName + "\\" + fileName) + "\r\n";
}
Application.DoEvents();
mes = "";
return true;
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "上传中出现错误:");
mes = ex.Message.ToString();
return false;
}
}
上传或下载文件方法并写入日志
最新推荐文章于 2023-04-16 14:00:02 发布