C# read path withoutI put / in each subfolder - c#

I want to put file path in File.Copy(path)
How can I put the path and not add / every time?
In python I can put r to read the path and not add /:
open(r"path")
Is there anything similar in C Sharp?

Yes you can use the # operator: var path = #"c:\\APath\bier";
these are called verbatim strings:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#regular-and-verbatim-string-literals
Edit:
Also when dealing with paths string interpolation may come in handy, in short its a way to substitute values in a string. Its the same as string.format but the syntax is better imo:
var hello = "Hello";
var world = "world";
var helloworldStringFormat = string.Format("{0} {1}", hello, world);
var helloworldStringInterpolation = $"{hello} {world}";
Also see: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#string-interpolation
Any ways you can do things like this:
var someValue = "bier";
var path3 = $"c:\\APath\\{someValue}";
var path4 = string.Format(#"c:\APath\{0}", someValue);
Also check out the Path class for dealing with paths, and optionally the Directory class.
https://learn.microsoft.com/en-us/dotnet/api/system.io.path?view=net-5.0
https://learn.microsoft.com/en-us/dotnet/api/system.io.directory?view=net-5.0

Related

C# variables inside of quotes

With string interpolation, how do you handle variables piped into a command that contain spaces in them? For example, if you have a variable that has spaces in it (like a UNC path), how do you handle that?
This code works when no spaces are present in the "filePath" variable (i.e.; \ServerName\testfile.txt):
Ex: System.Diagnostics.Process.Start("net.exe", $"use X: \\{filePath} {pwd /USER:{usr}").WaitForExit();
As soon as you encounter a path that has spaces in it, however, the command above no longer works, because it's unable to find the path. Normally, I would apply quotes around a path containing spaces, to counter this (in other languages like PowerShell). How do you do something similar with C# interpolation.
C# 6.0+:
System.Diagnostics.Process.Start("net.exe", #$"use X: \\Servername\share {pwd} /USER:{usr}").WaitForExit();
C# < 6.0:
System.Diagnostics.Process.Start("net.exe", #"use X: \\Servername\share " + pwd + " /USER: " + usr).WaitForExit();
use the $
void Main()
{
string pwd = "test";
var myVar = $"This is a {pwd}";
var folder = "MyFolder";
var myVarWithPaths = $"C:\\{folder}";
Console.WriteLine(myVar);
Console.WriteLine(myVarWithPaths);
}
Output
This is a test
C:\MyFolder
C# 6.0 introduced string interpolation, which is used by prefixing a quoted string of text with the $ character.
e.g.
var i = 0;
var s = $"i = {i}";
// output: i = 0
You can also embed multiple interpolated strings, as well as conditions.
var i = 0;
var s = $"i is: {(i == 1 ? $"i is {1}" : "i is not 1")}";
This can be combined with string literals that are prefixed with #.
var i = 1;
var s = #$"c:\{i}\test";
Basically, you can write almost any normal expression statement in a interpolated string, such as calling methods:
var s = $"i is {GetValueOfI() - 100}";
For types that are not a System.String, the implementation of that types ToString() method will be used for the resulting value.
See: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

Taking the last Substring of a string in C#

I have a string
"\uploads\test1\test2.file"
What's the method to get just "test2.file"?
What I have in my mind is to get the last index of "\" and then perform a string.substring(last index of "\") command on it?
Is there a method that takes just the word after the last "\"?
Use the method Path.GetFileName(path); in System.IO namespace, it is much more elegant than doing string operations.
You could use LINQ:
var path = #"\uploads\test1\test2.file";
var file = path.Split('\\').Last();
You might want to validate the input, if you're concerned about path potentially being null or whatnot.
You could do something like this:
string path = "c:\\inetpub\\wwwrroot\\images\\pdf\\admission.pdf";
string folder = path.Substring(0,path.LastIndexOf(("\\")));
// this should be "c:\inetpub\wwwrroot\images\pdf"
var fileName = path.Substring(path.LastIndexOf(("\\"))+1);
// this should be admin.pdf
For more take a look at here How do I get the last part of this filepath?
Hope it helps!
You can use the Split method:
string myString = "\uploads\test1\test2.file";
string[] words = myString.Split("\");
//And take the last element:
var file = words[words.lenght-1];
using linq:
"\uploads\test1\test2.file".Split('\\').Last();
or you can do it without linq:
string[] parts = "\uploads\test1\test2.file".Split('\\');
last_part=parts[parts.length-1]

How can I replace the same name of a file using regex but in another format?

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.

Getting part of the filename C#

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;

Splitting strings with slashes in C#

I have the following types of strings. One with three slashes and one with two:
a) filepath = "/F00C/Home/About"
b) filepath = "/Administration/Menus"
What I need to do is a function that will allow me to get the values of "home" and "administration" and put into topMenu variable and get the values of "Menus" and "About" and put this into the subMenu variable.
I am familiar with the function slashes = filePath.Split('/'); but my situation is not so simple as there are the two types of variables and in both cases I just need to get the last two words.
Is there a simple way that I could make the Split function work for both without anything to complex?
What's wrong with something like this ?
var splits = filePath.Split('/');
var secondLast = splits[splits.Length-2];
var last = splits[splits.Length-1];
Remarks:
Any check on the length of splits array (that must be >= 2) is missing.
Also, this code works only with forward-slash ('/'). To support both backslash and forward-slash separators, have a look at #Saeed's answer
Am I'm missing something or you just want:
var split = filepath.Split('/');
var last = split[split.Length -1];
var prev = split[split.Length -2];
var items = filePath.Split('/');
first = items[items.Length - 2];
second = items[items.Length - 1];
Also if this is a actual path you can use Path:
var dir = Path.GetDirectoryName(filePath);
dir = Path.GetFileName(dir);
var file = Path.GetFileName(filePath);
Edit: I edited Path version as the way discussed my digEmAll.

Categories

Resources