Is there a way of making strings file-path safe in c#?

how to give file path in c#
how to get relative path of a file in c#
how to get physical path of file in c#
getinvalidfilenamechars
c# sanitize filename
path combine c
c# make string safe for url
how to get file path in c#

My program will take arbitrary strings from the internet and use them for file names. Is there a simple way to remove the bad characters from these strings or do I need to write a custom function for this?

Ugh, I hate it when people try to guess at which characters are valid. Besides being completely non-portable (always thinking about Mono), both of the earlier comments missed more 25 invalid characters.

'Clean just a filename
Dim filename As String = "salmnas dlajhdla kjha;dmas'lkasn"
For Each c In IO.Path.GetInvalidFileNameChars
    filename = filename.Replace(c, "")
Next

'See also IO.Path.GetInvalidPathChars

PHP for the Web: Visual QuickStart Guide, File. Paths. There are two ways of referring to any file or directory on the computer: using An absolute path begins at the root ofthe computer: C:\somedir​\somefile.txt statement in a conditional, you make the PHP script attempt to write to the file only if The b flag is added so that the file is opened in a binary safe mode. My program will take arbitrary strings from the internet and use them for file names. Is there a simple way to remove the bad characters from these strings or do I need to write a custom function for

To strip invalid characters:

static readonly char[] invalidFileNameChars = Path.GetInvalidFileNameChars();

// Builds a string out of valid chars
var validFilename = new string(filename.Where(ch => !invalidFileNameChars.Contains(ch)).ToArray());

To replace invalid characters:

static readonly char[] invalidFileNameChars = Path.GetInvalidFileNameChars();

// Builds a string out of valid chars and an _ for invalid ones
var validFilename = new string(filename.Select(ch => invalidFileNameChars.Contains(ch) ? '_' : ch).ToArray());

To replace invalid characters (and avoid potential name conflict like Hell* vs Hell$):

static readonly IList<char> invalidFileNameChars = Path.GetInvalidFileNameChars();

// Builds a string out of valid chars and replaces invalid chars with a unique letter (Moves the Char into the letter range of unicode, starting at "A")
var validFilename = new string(filename.Select(ch => invalidFileNameChars.Contains(ch) ? Convert.ToChar(invalidFileNameChars.IndexOf(ch) + 65) : ch).ToArray());

Path.Combine Method (System.IO), The following example combines an array of strings into a path. Combine("c:\\", "*.txt") might be invalid if you were to create a file from it, it is valid as a search  Since Web.config may contain sensitive data such as connection strings, it is important that the contents of Web.config be kept safe and hidden from unauthorized viewers. By default, any HTTP request to a file with the .config extension is handled by the ASP.NET engine, which returns the This type of page is not served message shown in Figure 1.

This question has been asked many times before and, as pointed out many times before, IO.Path.GetInvalidFileNameChars is not adequate.

First, there are many names like PRN and CON that are reserved and not allowed for filenames. There are other names not allowed only at the root folder. Names that end in a period are also not allowed.

Second, there are a variety of length limitations. Read the full list for NTFS here.

Third, you can attach to filesystems that have other limitations. For example, ISO 9660 filenames cannot start with "-" but can contain it.

Fourth, what do you do if two processes "arbitrarily" pick the same name?

In general, using externally-generated names for file names is a bad idea. I suggest generating your own private file names and storing human-readable names internally.

C# Path Examples, Handle file locations in a consistent way. Taken all at once, the Path class might seem complicated and hard to use. IO; class Program { static void Main() { string path = @"C:\programs\file.txt"; // Get file name. string It is safe to cache it​. Stack Overflow Public I mention this because there can be a bunch of edge cases when dealing Is there a way of making strings file-path safe in c#?

I agree with Grauenwolf and would highly recommend the Path.GetInvalidFileNameChars()

Here's my C# contribution:

string file = @"38?/.\}[+=n a882 a.a*/|n^%$ ad#(-))";
Array.ForEach(Path.GetInvalidFileNameChars(), 
      c => file = file.Replace(c.ToString(), String.Empty));

p.s. -- this is more cryptic than it should be -- I was trying to be concise.

Windows Internals, Part 1, Callers can also modify the DLL search path for specific load operations by supplied to the API specifies a full path string, the path containing the DLL file is copy of the DLL in the application directory—either by creating a copy of the DLL with a copy of the local DLL in the folder (for example, C:\Program Files\​My App\. Most members of the Path class do not interact with the file system and do not verify the existence of the file specified by a path string. Path class members that modify a path string, such as ChangeExtension, have no effect on names of files in the file system.

Here's my version:

static string GetSafeFileName(string name, char replace = '_') {
  char[] invalids = Path.GetInvalidFileNameChars();
  return new string(name.Select(c => invalids.Contains(c) ? replace : c).ToArray());
}

I'm not sure how the result of GetInvalidFileNameChars is calculated, but the "Get" suggests it's non-trivial, so I cache the results. Further, this only traverses the input string once instead of multiple times, like the solutions above that iterate over the set of invalid chars, replacing them in the source string one at a time. Also, I like the Where-based solutions, but I prefer to replace invalid chars instead of removing them. Finally, my replacement is exactly one character to avoid converting characters to strings as I iterate over the string.

I say all that w/o doing the profiling -- this one just "felt" nice to me. : )

Expert SQL Server 2005 Development, StreamReader(FilePath)) { string line; while ((line = sr. finished the modifications, redeploy the outer assembly, making sure that it is cataloged as SAFE. The source data is fairly safe, but I don't want to make too many assumptions. EDIT: Just want to point out that in this case, I don't have a SqlConnection or any way to directly connect to SQL Server.

Foundations of Computer Security, To ensure that the virus will embed correctly in the program file, the virus writer has to check various locations in the file and find a safe location. Suppose that the virus writer wants the virus to infect files with programs A, B, or C. The virus An overwriting virus preserves the size of the infected file, but this doesn't make it​  Invalid Filename Check. Is there a quick way to ensure that the filename is valid before assigning it? Is there a way of making strings file-path safe in c#? 72.

How to Extract filename from a given path in C#, Here, path is the string from which we have to obtain the file name and extension. "c://myfiles//ref//file1.txt"; //function call to get the filename filename = Path. C# Path Examples Extract parts of paths with the Path class. Handle file locations in a consistent way.

filepath, The filepath package uses either forward slashes or backslashes, depending on the Constants: Variables: func Abs(path string) (string, error): func Base(path string) only if it represents a root directory, such as "/" on Unix or `C:\` on Windows. See also Rob Pike, “Lexical File Names in Plan 9 or Getting Dot-Dot Right,”  back to the top Write a Text File (Example 1) The following code uses the StreamWriter class to open, to write, and to close the text file. In a similar way to the StreamReader class, you can pass the path of a text file to the StreamWriter constructor to open the file automatically.

Comments
  • possible duplicate of Safe/Allowed filename cleaner for .NET
  • The C# version: foreach (var c in Path.GetInvalidFileNameChars()) { fileName=fileName.Replace(c, '-'); }
  • How would this solution handle name conflicts? It seems that more than one string can match to a single file name ("Hell?" and "Hell*" for example). If you are ok only removing offending chars then fine; otherwise you need to be careful to handle name conflicts.
  • what about the filesytem's limits of name (and path) length? what about reserved filenames (PRN CON)? If you need to store the data and the original name you can use 2 files with Guid names: guid.txt and guid.dat
  • One liner, for fun result = Path.GetInvalidFileNameChars().Aggregate(result, (current, c) => current.Replace(c, '-'));
  • @PaulKnopf, are you sure JetBrain does not have copyright to that code ;)
  • Although you are technically accurate, the GetInvalidFileNameChars is good for 80%+ of the situations you'd use it in, hence it's a good answer. Your answer would have been more appropriate as a comment to the accepted answer I think.
  • I agree with DourHighArch. Save the file internally as a guid, reference that against the "friendly name" which is stored in a database. Don't let users control your paths on the website or they will try to steal your web.config. If you incorporate url rewriting to make it clean it will only work for matched friendly urls in the database.
  • Why in the world would you use Array.ForEach instead of just foreach here
  • If you wanted to be even more concise / cryptic: Path.GetInvalidFileNameChars().Aggregate(file, (current, c) => current.Replace(c, '-'))
  • @BlueRaja-DannyPflughoeft Because you want to make it slower?
  • @Johnathan Allen, what makes you think foreach is faster than Array.ForEach ?
  • @rbuddicom Array.ForEach takes a delegate, which means it needs to invoke a function that can't be inlined. For short strings, you could end up spending more time on function call overhead than actual logic. .NET Core is looking at ways to "de-virtualize" calls, reducing the overhead.