Wednesday, May 23, 2007

C# File Open, Save in .Net Framework and Compact Framework

let's do C#:

1. Compact Framework:

private void btnOpenFile_Click(object sender, System.EventArgs e)
{
System.Windows.Forms.OpenFileDialog fd = new System.Windows.Forms.OpenFileDialog();
fd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
fd.FilterIndex = 1;

if(fd.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(fd.FileName);
// Insert code to read the stream here.
StreamReader str = new StreamReader(fd.FileName);

string tmp = str.ReadLine();
while(tmp!=null)
{
MessageBox.Show(tmp);
tmp = str.ReadLine();
}
str.Close();
}

}

private void btnSaveFile_Click(object sender, System.EventArgs e)
{
System.Windows.Forms.SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
sfd.FilterIndex = 1;
if(sfd.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(sfd.FileName);
string sfn = sfd.FileName;
if(sfn.Length > 4)
{
string sTmpFN = sfn.Substring(sfn.Length-4, 4);
MessageBox.Show(sfd.FileName);
if(sTmpFN != ".txt" )
sfn = sfn + ".txt";
}else
sfn = sfn + ".txt";
MessageBox.Show(sfn);
StreamWriter sw = new StreamWriter(sfn);
sw.WriteLine("Something!");
sw.Close();
}
}

2. .Net Framework:
private void button2_Click(object sender, System.EventArgs e)
{
Stream st;
System.Windows.Forms.OpenFileDialog fd = new System.Windows.Forms.OpenFileDialog();
fd.CheckPathExists = true;
fd.CheckFileExists = true;
fd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
fd.FilterIndex = 1;
fd.RestoreDirectory = true;

if(fd.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(fd.FileName);

if((st = fd.OpenFile())!= null)
{
// Insert code to read the stream here.
StreamReader str = new StreamReader(fd.FileName);

string tmp = str.ReadLine();
while(tmp!=null)
{
MessageBox.Show(tmp);
tmp = str.ReadLine();
}
str.Close();
st.Close();
}
}

}

private void button3_Click(object sender, System.EventArgs e)
{
System.Windows.Forms.SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
sfd.FilterIndex = 1;
if(sfd.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(sfd.FileName);
StreamWriter sw = new StreamWriter(sfd.FileName);
sw.WriteLine("Something!");
sw.Close();
}
}

No comments: