string path inside a directory of WPF c# solution - c#

I created a directory inside my WPF solution called Sounds and it holds sound files.(For example: mySound.wav).
Inside my code I use a List and there I have to add to those strings that relate to the sound files. In the beginning I used #"C:..." but I want it to be something like "UNIVERSAL" path. I tried using: "\Sounds\mySound.wav" but it generates an error.
The lines that I use there this directory are:
myList.Add("\Sounds\11000_0.2s.wav");//Error
using (WaveFileReader reader = new WaveFileReader(sourceFile))
where sourceFile is a string which express a path of the file.

Make sure that you check CopyToOutputDir in the properties of the soundfile, that will make sure the file is copied to the location you program runs from.
Also don't use single backslashes in the path since its an escape character.
Instead, do one of the following things:
Use a verbatim string:
#"Sounds\11000_0.2s.wav"
Escape the escape char:
"Sounds\\11000_0.2s.wav"
Use forward slashes:
"Sounds/11000_0.2s.wav"
For more information on string literals check msdn.

You either need to escape the / in the string or add the string literal indicator # at the beginning of the string.
Escape example:
var myFilePath = "c:\\Temp\\MyFile.txt";
String literal example:
var myFilePath = #"c:\Temp\MyFile.txt";

Related

Use Path.GetFileNameWithoutExtension method in C# to get the file name but the display is not complete

This is the simple C# code I wrote :
string file = #"D:\test(2021/02/10).docx";
var fileName = Path.GetFileNameWithoutExtension(file);
Console.WriteLine(fileName);
I thought I would get the string "test(2021/02/10)" , but I got this result "10)".
How can I solve such a problem?
I just wonder why would you want such behavior. On windows slashes are treated as separator between directory and subdirectory (or file).
So, basically you are not able to create such file name.
And since slashes are treated as described, it is very natural that method implementation just checks what's after last slash and extracts just filename.
If you are interested on how the method is implemented take a look at source code

Adding a character into a string after a specific character

In order to be able to read a file in asp.net, the file path must be written in this:
1.
C:\\yung\\Desktop
returns
however, the string that the fileUpload get returns is
2.
C:\yung\Desktop
After reading the comments i have this code:
string FilePath = FileUploadPublicInfo.PostedFile.FileName;
System.IO.StreamReader file = new System.IO.StreamReader(FilePath);
string line = File.ReadLines(FilePath.ToString()).Skip(4).ToString();
TextBox1.Text = line.ToString();
But now its giving this error:
System.Linq.Enumerable+<SkipIterator>d__30`1[System.String]
How to solve this problem?
Thank you.
I'm not so sure I understand the question, but I think you are looking for string.Replace:
string DoubleSlash(string singleSlash)
{
return singleSlash.Replace(#"\", #"\\");
}
The reason backslashes disappear is that C# compiler treats slashes in string literals as a special "escape" character. Because of this treatment, backslash needs to be encoded as two slashes in a regular string literal.
C# offers two ways of inserting backslashes the way you need:
Use verbatim literals - prefix it with "at" sign, i.e. #"C:\\yung\\Desktop", or
Double each slash - put two slashes for each slash in the result: C:\\\\yung\\\\Desktop
Ok, i have manage to solve this problem, turns out it was not reading anything.
This is the code that i finally get:
This is to retrieve the File's path, using this, would give the file path will double slash, so there is not a need for Replace(#"\",#"\")
string FilePath = FileUploadPublicInfo.PostedFile.FileName;
Then read the specified file
System.IO.StreamReader file = new System.IO.StreamReader(FilePath);
If you know which line you specifically want, this retrieves the 5th line
string line = File.ReadLines(FilePath.ToString()).Skip(4).First().ToString();
Thank you so much for your help...

Directory.GetFiles alters string path

Using System.IO, I tried the following code:
string[] files = Directory.GetFiles("\\folder\\folder_2\\folder_3");
And got the following exception:
"System.IO.DirectoryNotFoundException - It was not possible to locate part of the path 'C:\folder\folder_2\folder_3)' "
I don't know why "c:\" was added to the original string, and I can't seem to keep the method from doing so. What am I doing wrong?
Any help is much appreciated.
A backslash (\) at the start of a path makes it an absolute path. Remove the first \ if you want a relative path:
string[] files = Directory.GetFiles("folder\\folder_2\\folder_3");
You need to escape each of the beginning backslashes in your path, you only escaped a single slash. Use either correct escaping:
string[] files = Directory.GetFiles("\\\\folder\\folder_2\\folder_3");
Or you can use a verbatim string literal:
string[] files = Directory.GetFiles(#"\\folder\folder_2\folder_3");
Full explanation found in MSDN Documentation
In addition to the answers provided, you could use verbatim string literals, which will pass the string exactly without the need for escaping with all the messy backslashes.
In your case this would be
string[] files = Directory.GetFiles(#"folder\folder_2\folder_3");
Notice that the # is outside of quotes, but stuck to the opening quotes, this tells C# to use it, (pardon the pun) literally. The syntax highlighting for this kind of string will also change in Visual Studio, just FYI.
edit: saw a comment by another user advising you to use the #, it's the same thing. Sorry did not see this earlier.
Read about them here at MSDN

replace "\\' to '\' in C#

I'm using PayWay payment gateway.
I want to put the pay certificate File path in the web.config file.
so I add like this
<add key="PayWayPath" value="c:\payway\ccapi.q0&logDirectory=c:\payway"/>
the I call in my web form like this.
String initParams = WebConfigurationManager.AppSettings["PayWayPath"];
My initParams like this
initParams = c:\\payway\\ccapi.q0&logDirectory=c:\\payway
but I need to get like this output.
initParams = c:\payway\ccapi.q0&logDirectory=c:\payway
I try this things. But non of the work
initParams = initParams.Replace("\\\\", "\\");
initParams = Regex.Replace(initParams, #"[\\ ]", "\");
So how can I do it?
You don't need anything.
First one is only seems on IDE, when you write it, it will be without slashes..
Let's try it;
string s = "c:\\payway\\ccapi.q0&logDirectory=c:\\payway";
Console.WriteLine(s);
Output will be;
c:\payway\ccapi.q0&logDirectory=c:\payway
Here is a DEMO.
Irrelevant but if you want to write your strings exactly what they are, you can use # is called verbatim string literal
If i understand correctly, you won't need to do anything more. If the string already has the slashes escaped, when you "print" that value, it will appear as you want it to (ie. single slashes only)
You can do this by
initParams = initParams.Replace("\\\\", "\\");

Trim characters from a string

I need to trim a substring from a string, if that substring exists.
Specifically, if the string is "MainGUI.exe", then I need it to become "MainGUI", by trimming ".exe" from the string.
I tried this:
String line = "MainGUI.exe";
char[] exe = {'e', 'x', 'e', '.'};
line.TrimEnd(exe);
This gives me the correct answer for "MainGui.exe", but for something like "MainGUIe.exe" it doesn’t work, giving me "MainGUI" instead of "MainGUIe".
I am using C#. Thanks for the help!
Use the Path static class in System.IO namespace, it lets you strip extensions and directories from file names easily. You can also use it to get the extension, full path, etc. It's a very handy class and well worth looking into.
var filename = Path.GetFileNameWithoutExtension(line);
Gives you "MainGui", this is, of course, assuming you want to trim any file extension or you know your file is always going to be a .exe file, if you want to only trim extensions off of .exe files, however, and leave it on others. You can test first, either by using String.EndsWith() or by using the Path.GetExtension() method.
I would use Path.GetFileNameWithoutExtension instead of string manipulation to handle this.
string line = “MainGUI.exe”;
string fileWithoutExtension = Path.GetFileNameWithoutExtension(line);
If you only want to strip off the extension if it's .exe, you can check for that as well. The following will only strip off extensions of .exe, but leave all other extensions intact:
string ext = Path.GetExtension(line).ToLower();
string fileWithoutExtension = ext == ".exe"
? Path.GetFileNameWithoutExtension(line)
: line;
The Path class has a GetFileNameWithoutExtension.
If you are always trimming ".exe" you can trim the last 4 characters off regardless of the rest of the string.
line.Substring(0, line.Length - ".exe".Length);
string line = "MainGUI.exe";
if (line.EndsWith(".exe"))
line = line.Substring(0, line.Length - 4);
As no file extension has a dot (.) within it, you are safe to use this:
String line = "MainGUI.exe";
line = line.Substring(0, line.LastIndexOf('.'));

Categories

Resources