public partial class MainPage : UserControl |
{ |
#region Fields |
private SaveFileDialog dialog; |
#endregion |
|
#region Constructors |
public MainPage() |
{ |
InitializeComponent(); |
|
this.dialog = new SaveFileDialog(); |
|
try |
{ |
this.dialog.DefaultExt = ".txt"; |
this.dialog.Filter = "Text Files|*.txt|Log Files|*.log|All Files|*.*"; |
this.dialog.FilterIndex = 2; |
} |
catch ( Exception ex ) |
{ |
this.tblError.Text = "Error configuring SaveFileDialog: " + ex.Message; |
} |
} |
#endregion |
|
#region Handlers |
private void btnSaveFile_Click( object sender, RoutedEventArgs e ) |
{ |
bool? dialogResult = this.dialog.ShowDialog(); |
|
if ( dialogResult == true ) |
{ |
try |
{ |
FilesServiceReference.FilesClient fileClient |
= new FilesClient(); |
fileClient.GetFileCompleted |
+= new EventHandler<GetFileCompletedEventArgs>( |
fileClient_GetFileCompleted ); |
fileClient.GetFileAsync(“aa.xls”); |
|
this.tblError.Text = "Getting file from the server..."; |
} |
catch ( Exception ex ) |
{ |
this.tblError.Text = "Error calling service: " + ex.Message; |
} |
} |
} |
void fileClient_GetFileCompleted( object sender, GetFileCompletedEventArgs e ) |
{ |
try |
{ |
byte[] fileBytes = e.Result as byte[]; |
|
using ( Stream fs = ( Stream )this.dialog.OpenFile() ) |
{ |
fs.Write( fileBytes, 0, fileBytes.Length ); |
fs.Close(); |
|
this.tblError.Text = "File successfully saved!"; |
} |
} |
catch ( Exception ex ) |
{ |
this.tblError.Text = "Error getting result: " + ex.Message; |
} |
} |
#endregion |
|
}
WCF:
public byte[] GetFile(string fileName) { string filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/DownLoad")+@"\"+fileName; System.IO.FileStream sr = File.OpenRead(filePath); byte[] data = new byte[sr.Length];
int offset = 0; int remaining = data.Length; // 只要有剩余的字节就不停的读 while (remaining > 0) { int read = sr.Read(data, offset, remaining); if (read <= 0) {
break; } // 减少剩余的字节数 remaining -= read; // 增加偏移量 offset += read; } sr.Close(); return data;
|