Monday, October 5, 2009

Code4Food #2: Create a Text Editor in 5 minutes. C# - magic

Hi, guys!
It is October and it's the time for another Code4Food episode.

Today I'm gonna show you some magic. We'll make a text editor in C#.


Here is the sourcecode for Downloading:
ViewFile sourcecode


Note: This part will contain only loading certain file in a textbox.

1st minute.

a) Create a new WinForms app in Visual Studio (File -> New -> Project -> Windows Forms Application) and change the name of the project to ViewFile.


b) Delete the form Form1.cs from the solution.



c) Add a new form to the project and name it ViewFile


2nd minute

a) Open the ViewFile form in Designer mode. Add a textbox to this form and name it txtFileContent. Change it's 'Multiline' property to true, and 'ScrollBars' to 'Both'.


b) Change it's size to fit the form. After this change the 'Anchor' property to 'Top, Bottom, Left, Right'.


c) Add a button to the form and name it btnLoadFile and change it's 'Text' property to 'Load File'.
d) Add a button to the form and name it btnSaveFile and change it's 'Text' property to 'Save File'.

e) Add a label where we'll show the file name. Name it lblFileName and change it's 'Text' property to 'File Name'

f) In Program.cs change the following line so that your application runs the ViewFile form.
Application.Run(new ViewFile());

At this point you can run the User Interface of our app.


3rd minute

a) Create a private field _fileName where we'll store the name of the file we want to open. Create than a method where we'll initialize all the fields in our app and name it InitObjects. Initialize there _fileName to string.Empty. Also we'll make the filename label empty for now, because we don't have a file opened.

b) Double click the 'Load File' button and in the event generated by Visual Studio create an instance of OpenFileDialog. Set the properties of this instance: 'CheckFileExists' (verifies if the file exists) - true, 'Multiselect' (the ability to select multiple files in the dialog at once) - false. And call the method ShowDialog.

c) When the file is selected we'll show in the label only the name of the file which is stored in 'SafeFileName' property of the OpenFileDialog instance. Also save the full path to the file in _fileName field, and it is equal to 'FileName' property of the instance of the dialog.

Now our code should look like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ViewFile
{
public partial class ViewFile : Form
{
private string _fileName;

public ViewFile()
{
InitializeComponent();
InitObjects();
}

private void InitObjects()
{
lblFileName.Text = string.Empty;
_fileName = string.Empty;
}

private void btnLoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();

ofd.CheckFileExists = true;
ofd.Multiselect = false;

ofd.ShowDialog();

_fileName = ofd.FileName;
lblFileName.Text = ofd.SafeFileName;
}
}
}


4th minute

Now what we need to do is read the file and show its content in our textbox.
We'll use the StreamReader class, specifically its method ReadToEnd() and nested try-catch blocks to catch all the potential exceptions while we are trying to open a file.

So the final version of our app logic is this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ViewFile
{
public partial class ViewFile : Form
{
private string _fileName;

public ViewFile()
{
InitializeComponent();
InitObjects();
}

private void InitObjects()
{
lblFileName.Text = string.Empty;
_fileName = string.Empty;
}

private void btnLoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();

ofd.CheckFileExists = true;
ofd.Multiselect = false;

ofd.ShowDialog();

_fileName = ofd.FileName;
lblFileName.Text = ofd.SafeFileName;

if (_fileName != string.Empty)
LoadFileContent(_fileName);
}

private void LoadFileContent(string chosenFileName)
{
try
{
TextReader tr = new StreamReader(chosenFileName);
try
{ txtFileContent.Text = tr.ReadToEnd(); }
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
finally
{ tr.Close(); }
}
catch (System.IO.FileNotFoundException ex)
{ MessageBox.Show("Sorry, the file does not exist."); }
catch (System.UnauthorizedAccessException ex)
{ MessageBox.Show("Sorry, you lack sufficient privileges."); }
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
}
}
}

5th minute


For now we can really open any file but I wanted to make it look like a source code file. And disable some things we don't actually use.



a) We'll make the button 'Save File' disabled. Because we don't actually use it.

b) We'll change the 'Font' property of the txtFileContent to 'Courier New; 9pt'









No comments:

Post a Comment