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 =

//Open the file and extract the infomation into tempstr

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

//update the extracted data

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

//save the file inside your executing directory
DirectoryInfo dinfo =
+ "\\" + dinfo.Name,tempstr);

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

No comments: