WPF頁面:
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<TextBlock VerticalAlignment="Center" FontSize="16">版本更新</TextBlock>
<ProgressBar Name="PJinDu" Grid.Row="1"></ProgressBar>
<TextBlock Name="TJinDu" Grid.Row="2"></TextBlock>
</Grid>
CS文件
public partial class UpFile : Window
{
public UpFile()
{
InitializeComponent();
DownLoadFiles();
}
private void DownLoadFiles()
{
string fpath = "http://網址/文件名.exe";
string spath = Directory.GetCurrentDirectory() + "\\文件名.exe";
WebResponse response = null;
WebRequest request = WebRequest.Create(fpath);
response = request.GetResponse();
if (response == null) return;
PJinDu.Maximum = response.ContentLength;
ThreadPool.QueueUserWorkItem((obj) =>
{
Stream netStream = response.GetResponseStream();
Stream fileStream = new FileStream(spath, FileMode.Create);
byte[] read = new byte[1024];
long progressBarValue = 0;
int realReadLen = netStream.Read(read, 0, read.Length);
while (realReadLen > 0)
{
fileStream.Write(read, 0, realReadLen);
progressBarValue += realReadLen;
PJinDu.Dispatcher.BeginInvoke(new ProgressBarSetter(SetProgressBar), progressBarValue);
realReadLen = netStream.Read(read, 0, read.Length);
}
netStream.Close();
fileStream.Close();
}, null);
}
public delegate void ProgressBarSetter(double value);
public void SetProgressBar(double value)
{
PJinDu.Value = value;
TJinDu.Text = "已下載:" + (value / PJinDu.Maximum) * 100 + "%";
if (value >= PJinDu.Maximum)
{
Process isupdate = new Process();
isupdate.StartInfo.FileName = Directory.GetCurrentDirectory() + "\\文件名.exe";
isupdate.StartInfo.Arguments = "1";
isupdate.Start();
DialogResult = true;
}
}
}