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.
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 have a Path;
\\\\username-txd\location\Configuration\MediaManagerConfig\Web.config
I want to create a copy of file at one position up in the same folder i.e.
\\\\username-txd\location\Configuration\Web.config
Can anyone help me with the code since I am new to C#
DirectoryInfo.Parent returns this MediaManagerConfig and you can do little bit string manupalition like;
var di = new DirectoryInfo(#"\\\\username-txd\location\Configuration\MediaManagerConfig\Web.config");
Console.WriteLine(di.FullName.Replace(di.Parent.Name + Path.DirectorySeparatorChar, ""));
Result will be;
\\username-txd\location\Configuration\Web.config
If you want 4 back slash based on your result, your can replace with \\ to \\\\ as well.
You can use File.Copy to copy the file.
To get your destination file name, you can do
Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(path)), Path.GetFileName(path));
with 'path' the full path with the file name.
You need to import System.IO.
I would use seomthing like the power of the DirectoryInfo class. It knows the relationship on the filesystem and provides e.g. the .Parent property:
string originalFilename = "\\\\username-txd\\location\\Configuration\\MediaManagerConfig\\Web.config";
string originalPath = Path.GetDirectoryName(originalFilename);
string newPath = Path.Combine(new DirectoryInfo(originalPath).Parent.FullName, Path.GetFileName(originalFilename));
I am new in programming and not so good about regex. I wish to load / read a csv File and then save in a txt File using the same name of csv File. I will give an example.
D:\Project\File\xxx.csv
After I load this file, I want to get the name "xxx" and save it in a txt file:
D:\Project\File\xxx.txt
Or maybe in another folder, for example:
D:\Project\Specifications\PersonInfo.csv
save to
D:\Project\DataBank\PersonInfo.txt
This can be accomplished in many ways.
Maybe what you're lacking is knowledge of the System.IO.Path class (MSDN article here).
For instance changing the extension could be accomplished like so:
string originalFilePath = #"D:\Project\File\xxx.csv";
string newFilePath = Path.ChangeExtension(originalFilePath, ".txt");
Note: You need to explicitate the leading dot (".") for the extension.
Here's some "Path algebra" fun you could combine to create your desired effects:
string originalFilePath = #"D:\Project\File\xxx.csv";
string thePath = Path.GetDirectoryName(originalFilePath);
// will be #"D:\Project\File"
string filename = Path.GetFileName(originalFilePath);
// will be "xxx.csv"
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(originalFilePath);
// will be "xxx"
string recombinedFilePath = Path.Combine( #"D:\OtherFolder", "somethingElse.txt" );
// will be #"D:\OtherFolder\somethingElse.txt"
Note: Path.Combine knows how to handle extra/missing leading/trailing backslashes.
For example:
Path.Combine(#"D:\MyFolder1", #"MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1\", #"MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1", #"\MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1\", #"\MyFolder2\MyFile.txt")
will all yield the same result: #"D:\MyFolder1\MyFolder2\MyFile.txt"
You do not need regex for that, because .NET provides a System.IO.Path class for dealing specifically with file name manipulations.
For example, to replace .csv with .txt you can use this call:
var csvPath = #"D:\Project\File\xxx.csv";
var txtPath = Path.Combine(
Path.GetDirectoryName(csvPath)
, Path.GetFileNameWithoutExtension(csvPath)+".txt"
);
You use a similar trick to replace other parts of the file path. Here is how you change the name of the top directory:
var csvPath = #"D:\Project\Specifications\xxx.csv";
var txtPath = Path.Combine(
Path.GetDirectoryName(Path.GetDirectoryName(csvPath))
, "DataBank"
, Path.GetFileNameWithoutExtension(csvPath)+".txt"
);
You don't need Regex.
You can use Path.GetFileName or Path.GetFileNameWithoutExtension:
string fileName = Path.GetFileNameWithoutExtension("D:\Project\Specifications\PersonInfo.csv");
If you want to use regex for this, this regex will get the part you want:
([^\\]+)\.[^.\\]+$
The first group (in the parentheses) matches one or more characters (as many as possible) which is not a backslash. Then there need to be a literal dot. Then one or more characters (as many as possible) that are not a dot or backslash, then the end of the string. The group captures the wanted part.
I have a file name dayhappy_02_02345.csv
How do I get the 02 part out to be used in a variable and also how do I get the 02345 part so that I can pass these 2 values into a variable for a function.
Using c#.
I have looked at GetFileName but this gets either the filename, the extention or the full file name only.
Thanks
Ste
For that specific file name,
string sData = "dayhappy_02_02345.csv";
string[] sArr = sData.split('_');
string sPart1 = sArr[1];
string sPart2 = sArr[2];
Will do, but that's a special case, will work only on file names of this type
Get the file name as you've already figured out, then use String.Split() to get the individual pieces.
You have to use Regex:
var match = new Regex(#".*_(\d+)_(\d+)").Match(Path.GetFileNameWithoutExtension(fileNAme));
var v02 = match.Groups[0].Value;
var v02345 = match.Groups[1].Value;
I have a regex expression that I'm trying to construct that processes a file path and tries to find a file path whose directory ends with "Processed" or "Failed".
I have something like this...
static string PROCESSED_DIRECTORY = "Processed";
static string FAILURE_DIRECTORY = "Failed";
...
if (Regex.IsMatch(FileFullPath, String.Format(#"(.*)\\({0})|({1})$", PROCESSED_DIRECTORY, FAILURE_DIRECTORY)))....
This works fine.
However, I created an additional Regex expression because I am also trying to match the occurance of a file that is located in the Processed or Failed directory. The regex is not matching and I believe it has something to do with the pipe symbol. It matches when I check for either 'Failed' or 'Processed' without the pipe symbol.
For example: The following files don't match
- C:\ftp\business\Processed\file.txt
- C:\ftp|business\Failed\file.txt
I would expect them to match.
if (Regex.IsMatch(FileFullPath, String.Format(#"(.*)\\({0}|{1})\\(.*)", PROCESSED_DIRECTORY, FAILURE_DIRECTORY)))
If I somehow could combine the two Regex queries into one to say "Match a path that ends with Failed' or 'Processed' and also match a file that exists in the 'Failed' or 'Processed' directory", that'd be amazing. Right now though, I'm content with having two separate regex calls and getting the second to work.
Works ok for me... Ran this in LINQPad:
string PROCESSED_DIRECTORY = "Processed";
string FAILURE_DIRECTORY = "Failed";
string FileFullPath = #"C:\ftp\business\Processed\moof\file.txt";
Regex.IsMatch(FileFullPath, String.Format(#"(.*)\\({0}|{1})\\(.*)", PROCESSED_DIRECTORY, FAILURE_DIRECTORY)).Dump();
FileFullPath = #"C:\ftp|business\Failed\file.txt";
Regex.IsMatch(FileFullPath, String.Format(#"(.*)\\({0}|{1})\\(.*)", PROCESSED_DIRECTORY, FAILURE_DIRECTORY)).Dump();
Here's a version that will look for either containing the processed/failed strings OR ending in \Processed|Failed\filename.ext:
string PROCESSED_DIRECTORY = "ProcessedPath";
string FAILURE_DIRECTORY = "FailedPath";
string FileFullPath = #"C:\ftp\business\ProcessedPath\moof\file.txt";
Regex.IsMatch(FileFullPath, String.Format(#"((.*)\\({0}|{1})\\(.*))|(.*\\(Processed|Failed)\\(?!.*\\.*))", PROCESSED_DIRECTORY, FAILURE_DIRECTORY)).Dump();
FileFullPath = #"C:\ftp\business\NotTheProcessedPath\moof\Processed\file.txt";
Regex.IsMatch(FileFullPath, String.Format(#"((.*)\\({0}|{1})\\(.*))|(.*\\(Processed|Failed)\\(?!.*\\.*))", PROCESSED_DIRECTORY, FAILURE_DIRECTORY)).Dump();
There are quite a few ways to do this (progressively more complicated and more correct), but the simplest is probably this:
var targetStrings = new[] { PROCESSED_DIRECTORY, FAILURE_DIRECTORY }; //needles
string FileFullPath = #"C:\ftp\business\Processed\moof\file.txt"; //haystack
if (FileFullPath.Split('\\').Any(str => targetStrings.Contains(str)))
{
//...
No regex required. Regex seems overkill and possibly error-prone for this anyway.
System.IO.Path may be relevant to whatever you're doing here; it's what the Path class was made for.