0

Here is how I'm creating a file:

System.IO.File.Create(Server.MapPath("..") + name + ".html");

But sometimes name has illegal characters, like å, from the swedish alphabet. How to save them? It is possible directly, but I get error when I do it with code.

petko_stankoski
  • 10,459
  • 41
  • 127
  • 231
  • 4
    `å` is a valid character in a filename on Windows 7. What are you talking about? – Oded Mar 29 '12 at 15:38
  • http://stackoverflow.com/questions/309485/c-sharp-sanitize-file-name – drch Mar 29 '12 at 15:39
  • What error are you getting? Could you post the exact message and stack trace of the exception you are getting? Also the exact value of the name variable. – Darin Dimitrov Mar 29 '12 at 15:39
  • possible duplicate of [How to remove illegal characters from path and filenames?](http://stackoverflow.com/questions/146134/how-to-remove-illegal-characters-from-path-and-filenames) – BrokenGlass Mar 29 '12 at 15:39
  • 5
    You should not let users decide on the name of a file you save on the server file system. Instead use a unique id and store a mapping from user designated name to id e.g. in the DB – BrokenGlass Mar 29 '12 at 15:41

2 Answers2

3

If the path is user controlled and potentially contains invalid file system characters then you'll need to ask the user to change the name or normalize out the bad characters in a deterministic way. One method is to replace all invalid characters with say underscore.

public static string NormalizeFileName(string input) {
  var invalid = Path.GetInvalidPathChars();
  var builder = new System.Text.StringBuilder();
  foreach(char c in input) {
    if (invalid.Contains(c)) {
      builder.Append('_');
    } else {
      builder.Append(c);
    }
  }
  return builder.ToString();
}

You could then use this function as follows

var originalName = Server.MapPath("..") + name + ".html";
var normalizedName = NormalizeFileName(originalName);
System.IO.File.Create(normalizedName);

EDIT

As several people pointed out, it's best practice to use Path.Combine here to combine directory and file names.

var originalName = Path.Combine(Server.MapPath(".."), name + ".html");
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 1
    It'd probably fix some corner cases if he used `Path.Combine(Server.MapPath(".."), Path.ChangeExtension(NormalizeFileName(name), ".html"))`. – user7116 Mar 29 '12 at 15:44
0
System.IO.File.Create(Server.MapPath("..") + "\\" + name + ".html"); 
Serj-Tm
  • 16,581
  • 4
  • 54
  • 61