Removing file extension in asp.net - c#

How can I remove the extension file in asp.net something like filename.jpg to filename? I tried searching some reference but all I find is URL extension only

Use the System.IO.Path.GetFileNameWithoutExtension Method
The return value for this method is the string returned by GetFileName, minus the last period (.) and all characters following it.
string fileName = Path.GetFileNameWithoutExtension(fuImage.FileName); //file-name
string fileExt = Path.GetExtension(fuImage.FileName); //.jpg,.png....
string path_thumb = Path.Combine("Images/", string.Format("{0}{1}{2}", fileName, "-" + datetime + "-thumb", fileExt)); //full path: Images/file-name-012345-thumb.jpg

Related

Special chars in query string

I am passing a query string parameter containing file name.
default.aspx?file=Fame+ adlabs.xml (Fame+ adlabs.xml is the actual file name on server). The file name has "+" & also blank spaces.
When I check for file name from query string as follows:
var fileName = Request.QueryString["file"];
The variable filename does not have a "+" in it. It reads as "Fame adlabs.xml" & hence I get a file not found exception. I cannot rename the xml files. Can someone please guide me into right direction.
Thanks
If you are trying to do it at the server in C#:
String FileName = "default.aspx?";
String FullURL = FileName + HttpUtility.UrlEncode("Fame + adlabs.xml");
String Decoded = HttpUtility.UrlDecode(FullURL);
You should URL encode into your javascript before sending it :
var name = "Fame+ adlabs.xml";
var url = "default.aspx?file=" + encodeURIComponent(name);
Pay attention that following char won't work : ~!*()'

Path format is illegal

I want to ask about a easy question , but I faced a problem.
I want to get the time when the program is executed
Console.WriteLine(DateTime.Now);
And I want to output a .log file , the file name will have program execution time
String path2 = "C:\\temp"+DateTime.Now+".log";
StreamWriter path = File.CreateText(path2);
path.WriteLine(DateTime.Now);
But it is telling me Path format is illegal.
And I want ask another question
string a12 = aaa.Element("a12").tostring();
String path2 = "C:\\temp" + a12.ToString + ".log";
But it tell me "Path format is illegal"
How can I resolve it?
Thanks
That's because DateTime.Now converted to string by default contains time information (e.g. 8:53). Semicolon is illegal in path name.
If you meant only date to be in your file name, you could use:
String path2 = "C:\\temp" + DateTime.Now.ToString("d") + ".log";
(Edit) For some cultures this still can lead to invalid values, so as others pointed out, it is best to use explicit formatter:
String path2 = "C:\\temp" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
You want to escape your \ in the "" quoted string, and also there are characters in the result of DateTime.Now that cannot be in paths. You'll need to escape/replace those as well.
When you put DateTime.Now into a path, you risk adding characters that aren't valid as a path (like the : separator. That is the reason you get this error message.
You could replace it with a .:
string path2 = Path.Combine
( #"C:\temp\"
, DateTime.Now.ToString("yyyy-MM-dd.HH24.mm.ss")
, ".log"
);
DateTime.Now probably contains illegal characters depending on your local system settings. To get a valid and consistent file name independent on the culture the system is installed in you should create the log file name by hand, for instance like this:
String path2 = "C:\\temp" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log";
String path2 = String.Format("C:\\temp{0}.log", DateTime.Now.ToString("yyyyMMdd"));
Since filename cannot take "/" which was created by DateTime.Now.ToString("d") and hence creating issue.

C# getting first Characters of a file name

I have a directory name "C:\Folder\160_Name_2013111914447.7z" what I need is to extract the "160" from the file name in C# and use it to pass it to a MS-SQL method so I can move the file to a correct file Namely "160".
Please help, as I'm kinda new to C#.
Try something like this:
Path.GetFileName(#"C:\Folder\160_Name_2013111914447.7z").Split('_')[0];
Or possibly
string fileName = Path.GetFileName(#"C:\Folder\160_Name_2013111914447.7z");
Regex.Match(fileName, "^([0-9]+)_").Groups[1].Value;
If you need to take the first 3 symbols, you can use the Substring method of the string class:
string fileName = Path.GetFileName(#"C:\Folder\160_Name_2013111914447.7z");
// take 3 symbols starting from 0th character.
string extracted = fileName.Substring(0, 3);
If you can have variable length of key characters and the underscore character is the separator, then we'll have to modify the above code a little. First, we'll need the index of the underscore:
string fileName = Path.GetFileName(#"C:\Folder\160_Name_2013111914447.7z");
// get the zero-based index of the first occurrence of an underscore:
int underscoreIndex = fileName.IndexOf("_");
The string.IndexOf(...) methods returns -1 if match is not found, so we need to check for it.
if (underscoreIndex >= 0)
{
string extracted = fileName.Substring(0, underscoreIndex);
}
else
{
// no underscore found
throw new InvalidOperationException(
"Cannot extract data from file name: " + fileName);
}
To get the number assuming the file path you input will always be at the start and a length of 3 characters you can use.
FileInfo fileInfo = new FileInfo(path);
string name = fileInfo .Name;
int startingNumber = Convert.ToInt32(name.Substring(0,3));
where path is the full path of the file your using

The given path's format is not supported

I am trying to downlaod an excel sheet and I am dynamically generating its filename which has to be in the following format:
eg:
User_Wise_List_Of_Documents_2013_On_16_04_2013
For this I wrote the following code:
string currentDate = DateTime.Now.Date.ToString();
string currentYear=DateTime.Now.Year.ToString();
filename = Server.MapPath("~/User/Documents/") +
"User_Wise_List_Of_Documents_" + currentYear + "on" + currentDate +
".xls";
Somehow, its giving me the following exception:
The given path's format is not supported.
Any help will be appreciated.
I think your filename contains invalid chars like : Because you are forming filename with string currentDate = DateTime.Now.Date.ToString().
See the list for invalid chars
var invalidChars = Path.GetInvalidFileNameChars();
EDIT
You can use this to replace invalid chars
string newdatestr = String.Join("",currentDate.Select(c => invalidChars.Contains(c) ? '_' : c));
Have you checked the result of Server.MapPath("~/User/Documents/")?
It will return the directory path of your website's folder "/User/Documents/", which would be for example "C:\wwwroot\User\Documents\". You cant download a file from there (unless you're hosting local, in which case it might work, but for you only.
Probably you're looking for the Page.ResolveUrl() function, which will create a web uri relative to your website, rather than to the filesystem.

How do I verify that a string supplied file path is in a valid directory format?

I have a reasonably straight-forward question here but I seem to find myself revisiting each time I have to deal with the validation of file paths and names. So I'm wondering if there is a method available in System.IO or some other library in the framework that can make my life easier!?
Lets take the contrived example of a method that takes a file path and a filename and from these inputs it formats and returns unique full file-location.
public string MakeFileNameUnique(string filePath, string fileName)
{
return filePath + Guid.NewGuid() + fileName;
}
I know that I must do the following to get the path in a correct format so that I can append the guid and filename:
if filePath is null or empty then throw exception
if filePath does not exist then throw exception
if no valid postfixed '/' then add one
if it contains a postfixed '\' then remove and replace with a '/'
Can someone tell me if there is a framework method that can do this(particularly the forwareslash/backslash logic) available to achieve this repetitive logic?
Are you looking for the Path.Combine method:
public string MakeFileNameUnique(string filePath, string fileName)
{
return Path.Combine(filePath, Guid.NewGuid().ToString(), fileName);
}
but looking at the name of your method (MakeFileNameUnique), have you considered using the Path.GenerateRandomFileName method? Or the Path.GetTempFileName method?
Following your requirements this will do
public string MakeFileNameUnique(string filePath, string fileName)
{
// This checks for nulls, empty or not-existing folders
if(!Directory.Exists(filePath))
throw new DirectoryNotFoundException();
// This joins together the filePath (with or without backslash)
// with the Guid and the file name passed (in the same folder)
// and replace the every backslash with forward slashes
return Path.Combine(filePath, Guid.NewGuid() + "_" + fileName).Replace("\\", "/");
}
a call with
string result = MakeFileNameUnique(#"d:\temp", "myFile.txt");
Console.WriteLine(result);
will result in
d:/temp/9cdb8819-bdbc-4bf7-8116-aa901f45c563_myFile.txt
However I wish to know the reason about the replace for the backslash with forward slashes

Categories