Click here to Skip to main content
15,885,133 members
Articles / Programming Languages / C#
Article

Scratchpad: An Auto Save Notepad

Rate me:
Please Sign up or sign in to vote.
4.25/5 (9 votes)
27 Mar 2007CPOL2 min read 54.3K   1.1K   30   6
Scratchpad is a very simple Notepad-like editor that performs an automatic save every 5 minutes and when the application is closed.
Screenshot - scratchpad.jpg

Background

I always like to have an open text editor window where I write any idea that crosses my mind. But sometimes I forget to save this text when I shutdown the computer and consequently lose anything I had written.

To avoid this problem, I have written scratchpad which is a very simple text editor that automatically saves when the application is closed.

Features

Scratchpad supports the following features:

  1. When the application is started, it automatically re-opens the last edited file and restores the window position, size, and state.
  2. When the application is closed and every 5 minutes, the edited file is saved.
  3. To be able to recover the text in case of a computer crash during the save operation, a backup file is created.

The Code

Persistency of Window Position and Last Opened File

The following information needs to be made persistent:

  • The window position
  • The window size (in normal state)
  • The window state (maximized/minimized/normal)
  • The name of the edited file

To perform this persistence, I created a serializable class (PersistentData) that is used as a structure to contain all the data that requires persistency:

C#
[Serializable]
public class PersistentData
    {
    public int Top;
    public int Left;
    public int Width;
    public int Height;
    public string FilePath;
    public FormWindowState WindowState;
    }

To save the content of pData (the instance of PersistenData), I use the Serialize method:

C#
//save the context
//================
pData.WindowState = this.WindowState;

// Force the window to normal size to retrieve normal size bounds
this.WindowState = FormWindowState.Normal;
pData.Top = this.Top;
pData.Left = this.Left;
pData.Width = this.Width;
pData.Height = this.Height;

IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(Application.CommonAppDataPath + 
	@"\scratchpad.ini", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, pData );
            stream.Close();

Note 1: The path where to save the settings is obtained by a call to Application.CommonAppDataPath.

Note 2: To avoid saving the "maximized" size, the window is forced to "normal" size before reading its size and position.

To restore the persistent data, I use the Deserialize method. In case the deserialization fails (because the application setting file is not available), pData is initialized with default values:

C#
try 
  {
  IFormatter formatter = new BinaryFormatter();
  Stream stream = new FileStream(Application.CommonAppDataPath+@"\scratchpad.ini", 
		FileMode.Open, FileAccess.Read, FileShare.Read);
  pData = (PersistentData)formatter.Deserialize(stream);
  stream.Close();
  }
catch //deserialization failed
  {
  pData = new PersistentData();
  pData.Top = this.Top;
  pData.Left = this.Left;
  pData.Width = this.Width;
  pData.Height = this.Height;
  pData.WindowState = this.WindowState;
  pData.FilePath = "scatch.txt";
  }

Autosave Every 5 Minutes

The autosave every 5 minutes is done by a timer that triggers a save operation every 300,000ms if the text was modified since the last save.

C#
private void timer1_Tick(object sender, EventArgs e)
{
 if (textBox1.Modified)
     {
     Save();
     }
}

Note that the textbox1.modified flag is not automatically set or cleared by the framework, i.e. the application has to explicitly set and clear it.

Backup File Creation

To be sure that the data won't be corrupted even if the computer crashes during the save operation, I create a copy of the original file using File.Copy before performing any write operation on the edited file. Note: The try catch that is used to avoid the problem in case the edited file is a new file that does not exist yet on the disk is:

C#
//
//creates the backup
//===================
try
    {
    File.Copy(pData.FilePath,pData.FilePath+".bak",true);
    }
catch { /* ignore error */ }

// write the file
//=================
using (StreamWriter sw = new StreamWriter(pData.FilePath))
    {
    sw.Write(this.textBox1.Text);
    }

History

  • 27th March, 2007: Version 1.0 was created

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
Belgium Belgium
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Kuhan Muniam4-Jan-13 15:10
Kuhan Muniam4-Jan-13 15:10 
QuestionLooks good...but how can I install it? Pin
xtoq14-Jul-09 6:20
xtoq14-Jul-09 6:20 
AnswerRe: Looks good...but how can I install it? Pin
pierre poliakoff22-Jul-09 22:31
pierre poliakoff22-Jul-09 22:31 
GeneralGreat!!! Pin
davidvm21-May-09 9:13
davidvm21-May-09 9:13 
Generalnice Pin
vdfr123417-Nov-07 7:12
vdfr123417-Nov-07 7:12 
GeneralGood job Pin
thund3rstruck28-Mar-07 10:28
thund3rstruck28-Mar-07 10:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.