Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Sunday, August 10, 2008

.Net window form file uploader to webservice

Wanna Upload file in a asynchronise way in .Net ? Here I create a simple demo to upload your file to the webservice.
The code below is pretty useful especially creating three-tier applications and your desktop form application is not directly connecting to database.




public partial class FileUploader : Form
{
public FileUploader()
{
InitializeComponent();
}

private void btnBrowse_Click(object sender, EventArgs e)
{
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.Title = "Open File";
dialog.Filter = "All Files|*.*";
dialog.FileName = "";

try
{
dialog.InitialDirectory = "C:\\Temp";
}
catch
{
// skip it
}
dialog.ShowDialog();
if (dialog.FileName == "")
{
return;
}
else
{
txtFileName.Text = dialog.FileName;
}
}
}

private void UploadFile(string filename)
{

try
{
// get the exact file name from the path
String strFile = System.IO.Path.GetFileName(filename);

// create an instance of the web service
localhost_test.GetInfo ws = new formapp.localhost_test.GetInfo();
ws.Credentials = System.Net.CredentialCache.DefaultCredentials;

// get the file information form the selected file
FileInfo fInfo = new FileInfo(filename);

// get the length of the file to see if it is possible
// to upload it (with the standard 4 MB limit)

long numBytes = fInfo.Length;
double dLen = Convert.ToDouble(fInfo.Length / 1000000);

// Default limit of 128 MB on web server
// have to change the web.config to if
// you want to allow larger uploads
if (dLen < 128)
{

// set up a file stream and binary reader for the selected file
FileStream fStream = new FileStream(filename,FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);

// convert the file to a byte array
byte[] data = br.ReadBytes((int)numBytes);
br.Close();

// pass the byte array (file) and file name to the web service using asynchronise way
ws.UploadFileCompleted += new UploadFileCompletedEventHandler(this.UploadFileCompleted);
ws.UploadFileAsync(data, strFile);
fStream.Close();
fStream.Dispose();

//// pass the byte array (file) and file name to the web service using synchronise way
//string sTmp = ws.UploadFile(data, strFile);
//fStream.Close();
//fStream.Dispose();
//// this will always say OK unless an error occurs,
//// if an error occurs, the service returns the error message
//MessageBox.Show("File Upload Status: " + sTmp, "File Upload");
}
else
{
// Display message if the file was too large to upload
MessageBox.Show("The file selected exceeds the size limit for uploads.", "File Size");
}
}
catch (Exception ex)
{
// display an error message to the user
MessageBox.Show(ex.Message.ToString(), "Upload Error");
}
}

private void btnUpload_Click(object sender, EventArgs e)
{
if (txtFileName.Text != string.Empty)
{
UploadFile(txtFileName.Text);
}
else
{
MessageBox.Show("You must select a file first.", "No File Selected");
}
}

private void UploadFileCompleted(object sender, UploadFileCompletedEventArgs args)
{
//Bind returned results to the UI data grid
MessageBox.Show("File Upload Status: " + args.Result + " File Uploaded.");
}
}




Thursday, July 24, 2008

c# Asynchronous read write file

Quite often, you need to perform IO in .Net.
It is very useful that when coding windows form application, you perform asynchronous actions. Nobody like a freezing UI.
http://www.devsource.com/c/a/Using-VS/Making-Asynchronous-File-IO-Work-in-NET-A-Survival-Guide/



static void asyncWrite()
{
byte[] data = new byte[BUFFER_SIZE];
FileStream fs = new FileStream("writetest.dat", FileMode.Create,
FileAccess.Write, FileShare.None, 1, true);
try
{
// initiate an asynchronous write
Console.WriteLine("start write");
IAsyncResult ar = fs.BeginWrite(data, 0,
data.Length, null, null);
if (ar.CompletedSynchronously)
{
Console.WriteLine("Operation completed synchronously.");
}
else
{
// write is proceeding in the background.
// wait for the operation to complete
while (!ar.IsCompleted)
{
Console.Write('.');
System.Threading.Thread.Sleep(10);
}
Console.WriteLine();
}
// harvest the result
fs.EndWrite(ar);
Console.WriteLine("data written");
}
finally
{
fs.Close();
}
}