Wednesday, February 7, 2007

How to get the file from OpenFileDialog and copy the file in another directory?

Sometimes, your boss might ask you to read a product pricing file and manipulate it such as extracting the infomation and format it accordingly and save it back to a text file. In this case, the code below show you how u can use the .NET win control using OpenFileDialog class to provide a standard windows' open file dialog for your user to select a file and use the file to be manipulated. Here is the example:


using System.IO;

private void CopyFile2DirA()
{


// Create an OpenFileDialog
to request a file to open.
OpenFileDialog openFile1 =
openFileDialog1;


//Open the file and extract the infomation into tempstr

string tempstr = "";
using
(FileStream fs = (FileStream)openFile1.OpenFile())
{
byte[] b = new
byte[fs.Length];
UTF8Encoding temp = new UTF8Encoding(true);
while
(fs.Read(b, 0, b.Length) > 0)
{
tempstr += temp.GetString(b);
}
fs.Close();
}


//update the extracted data

tempstr += tempstr + " here some modified data.";

//save the file inside your executing directory
DirectoryInfo dinfo =
new
DirectoryInfo(openFile1.FileName);
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory
+ "\\" + dinfo.Name,tempstr);
}

That's it, now check the newly created file.

No comments: