Illegal character in output

2

I have an application that exports the result to me in a .csv file.

The export makes several project names, one of those projects has the tag name in HTML <b> .

When trying to create this file, I get an illegal character in path eror.

I have tried to put double quotes in the result:

"" + ProjectTitle + "" 

But the error keeps coming up.

How could I avoid getting this error and follow the execution of my program?

Thank you very much in advance.

    
asked by A arancibia 17.10.2016 в 17:00
source

4 answers

2

Using Linq, you can clean all illegal characters with a single line of code:

filename = Path.GetInvalidFileNameChars().Aggregate(filename, (current, c) => current.Replace(c.ToString(), string.Empty));
    
answered by 17.10.2016 / 17:36
source
1

File names have a series of characters that are not allowed. among them the major and minor symbols that are used for redirection.

I would use Path.GetInvalidFileNameChars to clean characters that are not allowed from the project name. Something like this:

string GetValidFileName(string projectTitle) {
  StringBuilder fileName = new StringBuilder();
  List<char> invalidChars = Path.GetInvalidFileNameChars().ToList();
  for (int i = 0; i < projectTitle.Length; i++) {
    char c = projectTitle[i];
    if (invalidChars.Contains(c))
      fileName.Add('_');
    else
      fileName.Add(c);
  }
  return fileName.ToString();
}
    
answered by 17.10.2016 в 17:30
0

The error is generated because there are many characters in the file names that are not allowed for fileName. For those file names in operating systems such as windows ** Only have A-Z characters, a-z, 0-9, spaces and in cases of not applying spaces use a hyphen under "_", or a simple hyphen "-"

You can try a solution a little simpler than the previous one posted.

string fileName = "ProjectTitle"; foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { fileName = fileName.Replace(c, '_'); }

This simple loop finds invalid characters in the filename and replaces them with "_"

    
answered by 17.10.2016 в 17:55
0

I recommend creating paths to files with the Combine method instead of concatenating strings:

rutaCompleta = Path.Combine(nombreCarpeta, Path.GetFileName(nombreArchivo.Replace("/","\")));

Combine Method

On this page you can see more methods for handling file names and routes (in English):

Dotnet Perls Path

    
answered by 03.11.2016 в 18:10