[c#] "The given path's format is not supported."

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?

This question is related to c# .net webforms upload stream

The answer is


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


Image img = Image.FromFile(System.IO.Path.GetFullPath("C:\\ File Address"));

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


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());

Try changing:

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

to

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


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.


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

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...!


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"


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.


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());

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];

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!


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to webforms

ASP.NET Button to redirect to another page How to use the DropDownList's SelectedIndexChanged event "Specified argument was out of the range of valid values" The ScriptManager must appear before any controls that need it Check if Cookie Exists How to do a Jquery Callback after form submit? "The given path's format is not supported." A potentially dangerous Request.Path value was detected from the client (*) How to create <input type=“text”/> dynamically Create a HTML table where each TR is a FORM

Examples related to upload

Upload file to SFTP using PowerShell This application has no explicit mapping for /error Schedule automatic daily upload with FileZilla jQuery AJAX file upload PHP How to find when a web page was last updated Summernote image upload on change event for file input element Multiple files upload in Codeigniter How to upload files on server folder using jsp How do I measure request and response times at once using cURL?

Examples related to stream

Why does calling sumr on a stream with 50 tuples not complete How to read/write files in .Net Core? How to get the stream key for twitch.tv Download TS files from video stream How to get streaming url from online streaming radio station Save byte array to file How to get error message when ifstream open fails Download large file in python with requests ASP.Net MVC - Read File from HttpPostedFileBase without save Fastest way to check if a file exist using standard C++/C++11/C?