核心功能模塊
public class DiaryEntry {
public DateTime Date { get; set; }
public string Title { get; set; }
public string Content { get; set; } // RTF 或純文本
public byte[] EncryptedData { get; set; } // 加密後存儲
}
關鍵技術點代碼片段
1. 文件加密存儲 (AES)
public static void SaveEncrypted(string path, string plainText, string password) {
using (var aes = Aes.Create()) {
var key = new Rfc2898DeriveBytes(password, salt: Encoding.UTF8.GetBytes("DiarySalt123"), iterations: 100000);
aes.Key = key.GetBytes(32); // AES-256
aes.IV = key.GetBytes(16);
using (var fs = File.Create(path))
using (var cs = new CryptoStream(fs, aes.CreateEncryptor(), CryptoStreamMode.Write))
using (var sw = new StreamWriter(cs, Encoding.UTF8)) {
sw.Write(plainText);
}
}
}
public static string LoadDecrypted(string path, string password) {
using (var aes = Aes.Create()) {
var key = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes("DiarySalt123"), 100000);
aes.Key = key.GetBytes(32);
aes.IV = key.GetBytes(16);
using (var fs = File.OpenRead(path))
using (var cs = new CryptoStream(fs, aes.CreateDecryptor(), CryptoStreamMode.Read))
using (var sr = new StreamReader(cs, Encoding.UTF8)) {
return sr.ReadToEnd();
}
}
}
2. RichTextBox 常用操作
// 復制/粘貼/剪切
richTextBox1.Copy();
richTextBox1.Paste();
richTextBox1.Cut();
// 查找 (返回找到位置)
int pos = richTextBox1.Find("關鍵字", RichTextBoxFinds.None);
if (pos >= 0) richTextBox1.Select(pos, "關鍵字".Length);
// 字體設置
richTextBox1.SelectionFont = new Font("微軟雅黑", 12, FontStyle.Bold);
richTextBox1.SelectionColor = Color.Blue;
// 保存/加載 RTF
richTextBox1.SaveFile(path, RichTextBoxStreamType.RichText);
richTextBox1.LoadFile(path, RichTextBoxStreamType.RichText);
3. 簡易主界面邏輯
public partial class MainForm : Form {
private string _currentFile;
private string _password;
private void NewDiary() {
using (var pwdDlg = new PasswordDialog()) {
if (pwdDlg.ShowDialog() == DialogResult.OK) {
_password = pwdDlg.Password;
richTextBox1.Clear();
_currentFile = null;
}
}
}
private void SaveDiary() {
if (_currentFile == null) SaveAsDiary();
else SaveEncrypted(_currentFile, richTextBox1.Rtf, _password);
}
private void OpenDiary() {
if (openFileDialog1.ShowDialog() == DialogResult.OK) {
using (var pwdDlg = new PasswordDialog()) {
if (pwdDlg.ShowDialog() == DialogResult.OK) {
try {
richTextBox1.Rtf = LoadDecrypted(openFileDialog1.FileName, pwdDlg.Password);
_currentFile = openFileDialog1.FileName;
_password = pwdDlg.Password;
} catch (CryptographicException) {
MessageBox.Show("密碼錯誤或文件損壞");
}
}
}
}
}
}
項目結構建議
DiaryApp/
├── Models/ // DiaryEntry, EncryptionHelper
├── Views/ // MainForm, PasswordDialog, AboutForm
├── Services/ // FileService, CryptoService
├── Resources/ // 圖標、默認模板
└── Program.cs // 入口,啟用視覺樣式、單實例鎖
現成開源參考
擴展方向
- 數據庫存儲 (SQLite) 替換單文件,支持標籤、全文檢索。
- 同步功能:OneDrive / Dropbox API / 自建 WebDAV。
- Markdown 編輯器 + 實時預覽 (用 Markdig + WebView2)。