122

I have the following code in my web service:

string str_uploadpath = Server.MapPath("/UploadBucket/Raw/");
FileStream objfilestream = new FileStream(str_uploadpath +
                fileName, FileMode.Create, FileAccess.ReadWrite);

Can someone help me resolve the issue with this error message from line 2 of the code.

The given path's format is not supported.

Permission on the folder is set to full access to everyone and it is the actual path to the folder.

The breakpoint gave me the value of str_uploadpath as C:\\webprojects\\webservices\\UploadBucket\\Raw\\.

What is wrong with this string?

sashoalm
  • 75,001
  • 122
  • 434
  • 781
All Blond
  • 1,243
  • 2
  • 8
  • 4

13 Answers13

139

Rather than using str_uploadpath + fileName, try using System.IO.Path.Combine instead:

Path.Combine(str_uploadpath, fileName);

which returns a string.

Justin
  • 84,773
  • 49
  • 224
  • 367
  • Got an error now:Error 4 A using namespace directive can only be applied to namespaces; 'System.IO.Path' is a type not a namespace – All Blond Sep 08 '11 at 13:32
  • 2
    @All Blond put `using System.IO;` above, then clear `str_uploadpath + fileName` and write `Path.Combine(str_uploadpath, fileName)` –  Sep 08 '11 at 13:35
  • code looks like below now, same error:The given path's format is not supported. string str_uploadpath = Server.MapPath(@"/UploadBucket/Raw/"); str_uploadpath = Path.Combine(str_uploadpath, fileName); FileStream objfilestream = new FileStream(str_uploadpath, FileMode.Create, FileAccess.ReadWrite); – All Blond Sep 08 '11 at 13:36
  • 1
    @All try to debug your code. Put a break point on the line exactly before the line that causes error (F9 in Visual Studio). Run your program. When the program stopps on the break point, hover the mouse on the variable `str_uploadpath`. What is its value? –  Sep 08 '11 at 13:52
  • As per Justin comment I looked at filename value. cleaned up filename to get absolute file name because actual value contained path to the file. And then combine with path as this suggested. Worked for me. Thanks – All Blond Sep 08 '11 at 14:00
  • 1
    I'm getting path not supported on the following path, why? "C:\Users\Admin\AppData\Local\Adobe\Flash CS6\en_US\Configuration\CodeModel\cm-cache\SwcCache\basemovie3.swc1272273593\library.swf" If I paste it in explorer, it opens fine, but .NET's System.IO.File.ReadAllBytes method throws that error. It's certainly a valid and accurate path, so why the error? – Triynko Sep 18 '12 at 18:43
  • @Triynko Do you use your path like this: `File.ReadAllBytes("C:\Users\Admin\AppData\Local\Adobe\Flash CS6\en_US\Configuration\CodeModel\cm-cache\SwcCache\basemovie3.swc1272273593\lib‌​rary.swf");` ? This is wrong. The correct is to use a @ before string to ignore specail character `'/'`. `File.ReadAllBytes(@"C:\Users\Admin\AppData\Local\Adobe\Flash CS6\en_US\Configuration\CodeModel\cm-cache\SwcCache\basemovie3.swc1272273593\lib‌​rary.swf");` –  Sep 18 '12 at 19:28
  • @Desolator: No, the string is already in memory as I posted it. It comes from a FileSystemWatcher event, so it's more like `File.ReadAllBytes( e.FullPath );` where e is an instance of FileSystemEventArgs. I couldn't make such a trivial error anyway, because that wouldn't even compile due to the invalid escape sequences. The string's contents is exactly as quoted (not including the quotes). – Triynko Sep 18 '12 at 20:52
  • It's not even like it's saying it's an invalid path, it's saying it's an "unsupported" "format", but I can't figure out why, because it looks like a relatively normal rooted path with no odd characters, aside from the "." in one of the directory names, but that should be legal. – Triynko Sep 18 '12 at 20:59
  • @Desolator in my case code working well on local but on server is giving same error – Meer Nov 09 '16 at 06:50
64

I see that the originator found out that the error occurred when trying to save the filename with an entire path. Actually it's enough to have a ":" in the file name to get this error. If there might be ":" in your file name (for instance if you have a date stamp in your file name) make sure you replace these with something else. I.e:

string fullFileName = fileName.Split('.')[0] + "(" + DateTime.Now.ToString().Replace(':', '-') + ")." + fileName.Split('.')[1];
  • 4
    This fixed an issue I've been having with my filename. I'm appending the current date and time to my file and and the ":" values were causing my program to throw the error OP referenced. – acedanger Jul 19 '13 at 19:42
  • 1
    This often happens by using `Path.GetInvalidPathChars` but not `Path.GetInvalidFileNameChars`, as was the case for me. – Seph Oct 08 '13 at 16:51
  • 6
    Thank you! This is why posting multiple answers is always a good idea. – Nick May 22 '14 at 19:28
52

For me the problem was an invisible to human eye "‪" Left-To-Right Embedding character.
It stuck at the beginning of the string (just before the 'D'), after I copy-pasted the path, from the windows file properties security tab.

var yourJson = System.IO.File.ReadAllText(@"D:\test\json.txt"); // Works
var yourJson = System.IO.File.ReadAllText(@"‪D:\test\json.txt"); // Error

So those, identical at first glance, two lines are actually different.

Oleg Grishko
  • 4,132
  • 2
  • 38
  • 52
24

If you are trying to save a file to the file system. Path.Combine is not bullet proof as it won't help you if the file name contains invalid characters. Here is an extension method that strips out invalid characters from file names:

public static string ToSafeFileName(this string s)
{
        return s
            .Replace("\\", "")
            .Replace("/", "")
            .Replace("\"", "")
            .Replace("*", "")
            .Replace(":", "")
            .Replace("?", "")
            .Replace("<", "")
            .Replace(">", "")
            .Replace("|", "");
    }

And the usage can be:

Path.Combine(str_uploadpath, fileName.ToSafeFileName());
ThiagoPXP
  • 5,362
  • 3
  • 31
  • 44
9

Among other things that can cause this error:

You cannot have certain characters in the full PathFile string.

For example, these characters will crash the StreamWriter function:

"/"  
":"

there may be other special characters that crash it too. I found this happens when you try, for example, to put a DateTime stamp into a filename:

AppPath = Path.GetDirectoryName(giFileNames(0))  
' AppPath is a valid path from system. (This was easy in VB6, just AppPath = App.Path & "\")
' AppPath must have "\" char at the end...

DateTime = DateAndTime.Now.ToString ' fails StreamWriter... has ":" characters
FileOut = "Data_Summary_" & DateTime & ".dat"
NewFileOutS = Path.Combine(AppPath, FileOut)
Using sw As StreamWriter = New StreamWriter(NewFileOutS  , True) ' true to append
        sw.WriteLine(NewFileOutS)
        sw.Dispose()
    End Using

One way to prevent this trouble is to replace problem characters in NewFileOutS with benign ones:

' clean the File output file string NewFileOutS so StreamWriter will work
 NewFileOutS = NewFileOutS.Replace("/","-") ' replace / with -
 NewFileOutS = NewFileOutS.Replace(":","-") ' replace : with - 

' after cleaning the FileNamePath string NewFileOutS, StreamWriter will not throw an (Unhandled) exception.

Hope this saves someone some headaches...!

FMFF
  • 1,652
  • 4
  • 32
  • 62
  • Ah thank you! I was saving a file with an ISO date string in the name, but that contains the illegal ":"! Thanks! – Mason Jan 16 '19 at 10:46
3

If you get this error in PowerShell, it's most likely because you're using Resolve-Path to resolve a remote path, e.g.

 Resolve-Path \\server\share\path

In this case, Resolve-Path returns an object that, when converted to a string, doesn't return a valid path. It returns PowerShell's internal path:

> [string](Resolve-Path \\server\share\path)
Microsoft.PowerShell.Core\FileSystem::\\server\share\path

The solution is to use the ProviderPath property on the object returned by Resolve-Path:

> Resolve-Path \\server\share\path | Select-Object -ExpandProperty PRoviderPath
\\server\share\path
> (Resolve-Path \\server\share\path).ProviderPath
\\server\share\path
Aaron Jensen
  • 25,861
  • 15
  • 82
  • 91
2

This was my problem, which may help someone else -- although it wasn't the OP's issue:

DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.ToString());

I determined the problem by outputting my path to a log file, and finding it not formatting correctly. Correct for me was quite simply:

DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.FullName.ToString());
omJohn8372
  • 154
  • 1
  • 6
2

Try changing:

Server.MapPath("/UploadBucket/Raw/")

to

Server.MapPath(@"\UploadBucket\Raw\")

SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
JimSTAT
  • 735
  • 1
  • 8
  • 27
1

I had the same issue today. The file I was trying to load into my code was open for editing in Excel. After closing Excel, the code began to work!

Ryano
  • 458
  • 4
  • 8
1

Does using the Path.Combine method help? It's a safer way for joining file paths together. It could be that it's having problems joining the paths together

Kurru
  • 14,180
  • 18
  • 64
  • 84
0

I am using the (limited) Expression builder for a Variable for use in a simple File System Task to make an archive of a file in SSIS.

This is my quick and dirty hack to remove the colons to stop the error: @[User::LocalFile] + "-" + REPLACE((DT_STR, 30, 1252) GETDATE(), ":", "-") + ".xml"

Adam Noël
  • 31
  • 2
0
Image img = Image.FromFile(System.IO.Path.GetFullPath("C:\\ File Address"));

you need getfullpath by pointed class. I had same error and fixed...

-1

If the value is a file url like file://C:/whatever, use the Uri class to translate to a regular filename:

var localPath = (new Uri(urlStylePath)).AbsolutePath

In general, using the provided API is best practice.

Chris Bordeman
  • 255
  • 7
  • 19