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?
Rather than using str_uploadpath + fileName, try using System.IO.Path.Combine instead:
Path.Combine(str_uploadpath, fileName);
which returns a string.
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];
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());
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...!
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
Try changing:
Server.MapPath("/UploadBucket/Raw/")
to
Server.MapPath(#"\UploadBucket\Raw\")
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());
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
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!
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"
Image img = Image.FromFile(System.IO.Path.GetFullPath("C:\\ File Address"));
you need getfullpath by pointed class. I had same error and fixed...
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.
Related
I am developing an internal application which sends email to the users with the link to the training dcouments.
These documnets are placed in internal share drive, few of these documents have empty space in their names and thats causing the problem.
The path looks like \\Users\shared\Training\Database\Oracle\Docs\Oracle Database Admin.docx and i tried to replace empty space with %20 but still it doesn't work.. In the email link the path is trimmed to \\Users\shared\Training\Database\Oracle\Docs\Oracle
Public string GetMediaPath(int itemCode)
{
string path = _dbContext.TraningMedias.Where( s => s.ItemCode == itemCode).Select(a => a.Path).FirstOrDefault().ToString();
path.replace(" ", "%20");
return path;
}
I dont understand why the replace function is not working in this case.
Strings are immutable, and Replace returns a string, so try this:
path = path.Replace(" ", "%20");
To preserve the spaces in your link text, use an opening and closing chevron
Public string GetMediaPath(int itemCode)
{
string path = "<"+ _dbContext.TraningMedias.Where( s => s.ItemCode == itemCode).Select(a => a.Path).FirstOrDefault().ToString() + ">";
return path;
}
Try doing this:
The below code will remove all invalid filename characters from the path.
path =string.Concat(path.Split(Path.GetInvalidFileNameChars()));
Dont forget to include System.IO namespace.
Thanks
You can try url encode adn get rid off spaces and others speacial characters.
path= HttpUtility.UrlDecode(path);
Just convert the raw file path string to a proper URI, like this:
string fileUrl = new System.Uri("c:\\foo\\my document.docx").AbsoluteUri
which will give you this string:
"file:///c:/foo/my%20document.docx"
Look this
In your case:
path = Uri.EscapeUriString(path);
I am creating an Image Extraction tool and I am able to retrieve the Images with full path..
For Example:
I need to cut the File name (rss) from path...
I search posts and Tried following
//1.
//string str = s.Split('/', '.')[1];
//2.
string s1;
// string fileName = "abc.123.txt";
int fileExtPos = s.LastIndexOf(".");
if (fileExtPos >= 0)
s1 = s.Substring(0, fileExtPos);
//3.
//var filenames = String.Join(
// ", ",
// Directory.GetFiles(#"c:\", "*.txt")
// .Select(filename =>
//4.
// Path.GetFileNameWithoutExtension(filename)));
None seems to be working
I want the name between "images" and "png" ..What can be the exact code?
Any Suggestion will be helpful
Just use the class Path and its method GetFileNameWithoutExtension
string file = Path.GetFileNameWithoutExtension(s);
Warning: In this context (just the filename without extension and no arguments passed after the URL) the method works well, however this is not the case if you use other methods of the class like GetDirectoryName. In that context the slashes are reversed into Windows-style backslashes "\" and this could be an error for other parts of your program
Another solution, probably more WEB oriented is through the class Uri
Uri u = new Uri(s);
string file = u.Segments.Last().Split('.')[0];
but I find this a lot less intuitive and more error prone.
In your example you're using a uri so you should use System.Uri
System.Uri uri = new System.Uri(s);
string path = uri.AbsolutePath;
string pathWithoutFilename = System.IO.Path.GetDirectoryName(path);
Why use Uri? Because it will handle things like
http://foo.com/bar/file.png#notthis.png
http://foo.com/bar/file.png?key=notthis.png
http://foo.com/bar/file.png#moo/notthis.png
http://foo.com/bar/file.png?key=moo/notthis.png
http://foo.com/bar/file%2epng
Etc.
Here's a fiddle
You should use the various System.IO.Path functions to manipulate paths as they work cross platform. Similarly you should use the System.Uri class to manipulate Uris as it will handle all the various kinds of edge cases like escaped characters, fragments, query strings, etc.
Trying to get a file path from user via cmd input. Want to make sure that there is a "/" or "\" at the end of the file path. Here is my code:
Console.WriteLine("Please specify file location:");
string fileLocation = #Console.ReadLine();
fileLocation = fileLocation.PadRight(1, '/');
However when testing it doesn't seem to add the character. What is wrong? Is there a better way to do this?
Thanks!
I don't think that you actually want to use PadRight
Returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified Unicode character.
What about just checking for it and appending it to the end of the string if it doesnt exist instead:
if(!fileLocation.EndsWith("/"))
{
fileLocation += "/";
}
Um trying to create a pdf file with the file name as follows
Hello 1115 Apple Mango 27.08.2015 00:00:00.pdf
using
var tempFileName = Fruit.Name + " " + numberName + " " + DateTime.Now.Date.ToString() + ".pdf";
var pdfFile = Path.Combine(Path.GetTempPath(), tempFileName);
System.IO.File.WriteAllBytes(pdfFile, Pdfcontent.GetBuffer());
Please note that my file name contain spaces, if I create a file name without spaces it will generate a file without any issues
Since it's containing spaces it throws an exception {"The given path's format is not supported."}
The Generated filepath looks something like this
C:\Users\Sansa\AppData\Local\Temp\Hello 1115 Apple Mango 27.08.2015 00:00:00.pdf
How to fix this issue
: are not allowed in the file names. You could remove them.
Also you could replace spaces with the underscores _ if you want.
The problem isn't in spaces. There are a few symbols, that deniend in naming: <, >, :, ", /, \, |, ?, *. Also you can check the rules for naming files and folders on MSDN.
You can fix this issue by replacing this symbols to allowed. In your case you can use simple replace:
tempFileName = tempFileName.Replace(':', '_'); // prevent using : symbol
But much better is to get all unallowed symbols and use Regex to prevent using them:
var pattern = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
var r = new Regex(string.Format("[{0}]", Regex.Escape(pattern)));
tempFileName = r.Replace(tempFileName, "_");
If you choose second variant, don't forget to add namespaces in your file:
using System.IO;
using System.Text.RegularExpressions;
Alright, so my question is; I'm trying to save a file to the C: drive in a folder. Now, I know how to do this for regular files like
using(StreamWriter writer = new SteamWriter("c:\\Folder\\TextFile.txt");
What I've been trying to figure out is how I can make it so that the name of text file is the replaced with a variable so Its more like
using(StreamWriter writer = new SteamWriter("c:\\Folder\\Variablegoeshere.txt");
Is there anyway I can do this?
I apologize for my poor question asking skills.
The StreamWriter constructor, like many other constructors and method calls, takes a string argument. You can pass it any string you like. In your first code sample, you're passing the constructor a "string literal" - an unnamed string variable with a constant value. Instead, you can pass a standard string variable, that you construct beforehand. For instance:
string name = // whatever you like
string path = "c:\\Folder\\" + name + ".txt"; // use '+' to combine strings
using (StreamWriter writer = new SteamWriter(path));
I usually like to use the Path.Combine static method when I concatenate path components. Helps me avoid problems with missing or doubled backslashes:
string path = System.IO.Path.Combine("c:\\Folder", name + ".txt");
And, finally, with the string verbatim modifier, you avoid those ugly double-backslashes, that are otherwise necessary because the backslash is the "escape" character in non-verbatim strings:
string path = System.IO.Path.Combine(#"c:\Folder", name + ".txt");
Here's the Microsoft developer reference page for strings in C#. Worth a read, as is the larger C# language reference.
var inputPath = "c:\\Folder\\TextFile.txt";
var folderPath = Path.GetDirectoryName( inputPath );
using ( var writer = new StreamWriter ( Path.Combine( folderPath, "Variablegoeshere.txt" ) )