-1

I have a program where you can write notes and save them in .txt files. Every note has a title and a text. The title of the note is the file name without ".txt" suffix. So in my program there's a Listbox that contains all the notes'title and clicking on the title you can read the note. My problem is that I can't write a title with these characters: \ / : * ? " < > | because they're not allowed in a file name.

How could I solve this problem? I thought that a solution could be to create a new .txt file that contains only file names then associate a file name to a note based on the line number.

Is there an easier solution? If yes, could you please tell me? Thank you!

Abbas
  • 14,186
  • 6
  • 41
  • 72
DarioDP
  • 627
  • 2
  • 9
  • 24

4 Answers4

2

The advantage of a separate index file is that you can get all the titles easily. The disadvantage is that it can get out of date unless you are very careful, and you restrict access to the underlying file system.

Personally, I'd probably be tempted to make the first line of each text file the title, and make the file-name the sanitized title. That means you can display something very close to the actual title very quickly, but you have the option to async loop over the files and update the actual titles if they are different... i.e. if the title the user entered was "what < do ! I do?" they might see "what do I do" very briefly, quickly replaced by "what < do ! I do?" - and no risk of index file damage.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

You can maintain a Dictionary of Special characters with your unique strings, Something like:

Dictionary<string, string> specialCharDictionary = new Dictionary<string, string>();
specialCharDictionary.Add("\\", "Slash");
specialCharDictionary.Add("/", "BSlash");
//....

and then use that to create and access file name.

Habib
  • 219,104
  • 29
  • 407
  • 436
0

You could either base-64 encode the filename or make the files XML instead of plain text, and encode the entities.

Echilon
  • 10,064
  • 33
  • 131
  • 217
0

Is the title given by the user? If so, there's an easy way to validate the title. Just check if the given title contains one of the prohibited characters. Then you can either remove them and use the stripped result or you could show the user an error-message stating that those characters are not allowed.

This question provides the answer regarding finding special chars in a string. Hope this helps!

Community
  • 1
  • 1
Abbas
  • 14,186
  • 6
  • 41
  • 72