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
Related
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 : ~!*()'
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
How can I split a string from the end to some character I want.
Let me explain in example
"C:\Users\Esat\Desktop\BilimResimler\1620855_759701257391419_1132489417_n.jpg"
and I want to cut this part 1620855_759701257391419_1132489417_n.jpg but I have a lot of image and image names always changing so i can not use substring metod.So how can i do this ?
just to add to the answers - if this refers to a file that physically exists on disk, then why not let fileinfo do the work for you?
var path = #"C:\Users\Esat\Desktop\BilimResimler\1620855_759701257391419_1132489417_n.jpg";
System.IO.FileInfo myImageFile = new System.IO.FileInfo(path);
Console.WriteLine(myImageFile.Name); // gives 1620855_759701257391419_1132489417_n.jpg
You can search for the last "\" character and eliminate everything from it, including him.
OR
From 0 to the index of the length of "C:\Users\Esat\Desktop\BilimResimler\" - 1 (37 - 1 if I counted correctly) keep the string and eliminate everything else.
This should do it
string imageNameAndPath=#"C:\Users\Esat\Desktop\BilimResimler\1620855_759701257391419_1132489417_n.jpg"
imageNameAndPath=imageNameAndPath.Substring(0, imageNameAndPath.LastIndexOf('/'));
string FileName = Path.GetFileName(Path)
You can also get your file name using below code.
var path = #"C:\Users\Esat\Desktop\BilimResimler\1620855_759701257391419_1132489417_n.jpg";
string ImgPath = path.Substring(path.LastIndexOf(#"\") + 1);
I have a list of filename with full path which I need to remove the filename and part of the file path considering a filter list I have.
Path.GetDirectoryName(file)
Does part of the job but I was wondering if there is a simple way to filter the paths using .Net 2.0 to remove part of it.
For example:
if I have the path + filename equal toC:\my documents\my folder\my other folder\filename.exe and all I need is what is above my folder\ means I need to extract only my other folder from it.
UPDATE:
The filter list is a text box with folder names separated by a , so I just have partial names on it like the above example the filter here would be my folder
Current Solution based on Rob's code:
string relativeFolder = null;
string file = #"C:\foo\bar\magic\bar.txt";
string folder = Path.GetDirectoryName(file);
string[] paths = folder.Split(Path.DirectorySeparatorChar);
string[] filterArray = iFilter.Text.Split(',');
foreach (string filter in filterArray)
{
int startAfter = Array.IndexOf(paths, filter) + 1;
if (startAfter > 0)
{
relativeFolder = string.Join(Path.DirectorySeparatorChar.ToString(), paths, startAfter, paths.Length - startAfter);
break;
}
}
How about something like this:
private static string GetRightPartOfPath(string path, string startAfterPart)
{
// use the correct seperator for the environment
var pathParts = path.Split(Path.DirectorySeparatorChar);
// this assumes a case sensitive check. If you don't want this, you may want to loop through the pathParts looking
// for your "startAfterPath" with a StringComparison.OrdinalIgnoreCase check instead
int startAfter = Array.IndexOf(pathParts, startAfterPart);
if (startAfter == -1)
{
// path not found
return null;
}
// try and work out if last part was a directory - if not, drop the last part as we don't want the filename
var lastPartWasDirectory = pathParts[pathParts.Length - 1].EndsWith(Path.DirectorySeparatorChar.ToString());
return string.Join(
Path.DirectorySeparatorChar.ToString(),
pathParts, startAfter,
pathParts.Length - startAfter - (lastPartWasDirectory?0:1));
}
This method attempts to work out if the last part is a filename and drops it if it is.
Calling it with
GetRightPartOfPath(#"C:\my documents\my folder\my other folder\filename.exe", "my folder");
returns
my folder\my other folder
Calling it with
GetRightPartOfPath(#"C:\my documents\my folder\my other folder\", "my folder");
returns the same.
you could use this method to split the path by "\" sign (or "/" in Unix environments). After this you get an array of strings back and you can pick what you need.
public static String[] SplitPath(string path)
{
String[] pathSeparators = new String[]
{
Path.DirectorySeparatorChar.ToString()
};
return path.Split(pathSeparators, StringSplitOptions.RemoveEmptyEntries);
}
I'd like to trim these purchase order file names (a few examples below) so that everything after the first "_" is omitted.
INCOLOR_fc06_NEW.pdf
Keep: INCOLOR (write this to db as the VendorID) Remove: _fc08_NEW.pdf
NORTHSTAR_sc09.xls
Keep: NORTHSTAR (write this to db as the VendorID) Remove: _sc09.xls
Our scenario: The managers are uploading these files to our Intranet web server, to make them available to download/view ect. I'm using Brettles NeatUpload, and for each file uploaded, am writing the files attributes into the PO table (sql 2000). The first part of the file name will be written to the DB as a VendorID.
The naming convention for these files is consistent in that the the first part of the file is always the vendor name (or Vendor ID) followed by an "_" then other unpredictable chars used to identify the type of Purchase Order then the file extention - which is consistently either .xls, .XLS, .PDF, or .pdf.
I tried TrimEnd - but the array of chars that you have to provide ends up being long and can conflict with the part of the file name I want to keep. I have a feeling I'm not using TrimEnd properly.
What is the best way to use string.TrimEnd (or any other string manipulation in C#) that will strip off all chars after the first "_" ?
String s = "INCOLOR_fc06_NEW.pdf";
int index = s.IndexOf("_");
return index >= 0 ? s.Substring(0,index) : s;
I'll probably offend the anti-regex lobby, but here I go (ducking):
string stripped = Regex.Replace(filename, #"(?<=[^_]*)_.*",String.Empty);
This code will strip all extra characters after the first '_', unless there is no '_' in the string (then it will just return the original string).
It's one line of code. It's slower than the more elaborate IndexOf() algorithm, but when used in a non-performance-sensitive part of the code, it's a good solution.
Get your flame-throwers out...
TrimEnd removes white spaces and punctuation marks at the end of the String, it won't help you here. Read more about TrimEnd here:
http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx
Bnaffas code (with a small tweak):
String fileName = "INCOLOR_fc06_NEW.pdf";
int index = fileName.IndexOf("_");
return index >= 0 ? fileName.Substring(0, index) : fileName;
If you want to do something with the other parts, you could use a Split
string fileName = "INCOLOR_fc06_NEW.pdf";
string[] parts = fileName.Split('_');
public string StripOffStuff(string sInput)
{
int iIndex = sInput.IndexOf("_");
return (iIndex > 0) ? sInput.Substring(0, iIndex) : sInput;
}
// Call it like:
string sNewString = StripOffStuff("INCOLOR_fc06_NEW.pdf");
I would go with the SubString approach but to round out the available solutions here's a LINQ approach just for fun:
string filename = "INCOLOR_fc06_NEW.pdf";
string result = new string(filename.TakeWhile(c => c != '_').ToArray());
It'll return the original string if no underscore is found.
To go with all the "alternative" solutions, here's the second one that I thought of (after substring):
string filename = "INCOLOR_fc06_NEW.pdf";
string stripped = filename.Split('_')[0];