C# PadRight Backslash or Frontslash - c#

Trying to get a file path from user via cmd input. Want to make sure that there is a "/" or "\" at the end of the file path. Here is my code:
Console.WriteLine("Please specify file location:");
string fileLocation = #Console.ReadLine();
fileLocation = fileLocation.PadRight(1, '/');
However when testing it doesn't seem to add the character. What is wrong? Is there a better way to do this?
Thanks!

I don't think that you actually want to use PadRight
Returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified Unicode character.
What about just checking for it and appending it to the end of the string if it doesnt exist instead:
if(!fileLocation.EndsWith("/"))
{
fileLocation += "/";
}

Related

c# - Handle empty spaces in file name while providing the file path as a link

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);

How do I use an illegal character?

public void CreateCertificate()
{
File.Create($"
{#"C:\Users\Director\Documents\TestCertApp\TestSub\" + thisYear +
" Certificates- " + certType + "\""}{myFileName}.ppt", 1 ,
FileOptions.None);
}
So I need the backslash between certype and filename to show it belongs within the folder and not next to. It says its an illegal character but how would I get the file in the folder without it?
Based on the code that you wrote the file path that will be generated is (based on my own substitutions for the variables):
String thisYear = "2019";
String certType = "UnderGrad";
String myFileName = "myfile";
String fileToCreate = $"{#"C:\Users\Director\Documents\TestCertApp\TestSub\" + thisYear + " Certificates- " + certType + "\""}{myFileName}.ppt";
Debug.Print(fileToCreate);
Will give you this output:
C:\Users\Director\Documents\TestCertApp\TestSub\2019 Certificates- UnderGrad"myfile.ppt
If you notice there is a " before the filename part of myfile.ppt - This is where the Illegal Character comes from.
If you use this code fragment to generate the path:
String basePath = #"C:\Users\Director\Documents\TestCertApp\TestSub\";
String certificateFolder = $"{thisYear} Certificates- {certType}";
String correctFilePath = Path.Combine(basePath, certificateFolder, $"{myFileName}.ppt");
Debug.Print(correctFilePath);
This will result in the output of:
C:\Users\Director\Documents\TestCertApp\TestSub\2019 Certificates- UnderGrad\myfile.ppt
This version has a \ where the previous code had a " and is no longer illegal, but conforms to the requirement that you wrote the files being in the folder.
Something else to note:
You may want to use Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); to get the path to the MyDocuments folder of the user.
Well, the short answer is that you cannot use an illegal character in a path or file name. Otherwise it wouldn't be illegal. :)
But it seems that the problem here is that you though you were adding a backslash (\) character, when really you were adding a double quote (") character. So if everything else is ok, you can just replace "\"" with "\\" and it should work.
Part of the problem is also that you're doing some strange combination of string interpolation, and it makes the code really hard to read.
Instead you can use just string interpolation to simplify your string (I had to use concatenation below to prevent horizontal scrolling, but you could remove it):
string filePath = $#"C:\Users\Director\Documents\TestCertApp\TestSub\{thisYear} " +
$#"Certificates- {certType}\{myFileName}.ppt";
But even better would be to use the Path.Combine method, along with some variables, to make the intent very clear:
var rootDir = #"C:\Users\Director\Documents\TestCertApp\TestSub"
var fileDir = $"{thisYear} Certificates- {certType}"
var fileName = "{myFileName}.ppt";
var filePath = Path.Combine(rootDir, fileDir, fileName);

How can we remove certain folder name from the path and return new path?

I have a path:
"C:\\Users\\dev\\Test\\TestResults\\Config\\Report.xml"
I need to check if this path has folder "TestResults", if it has then I need to remove this and return new path as
"C:\\Users\\dev\\Test\\Config\\Report.xml"
I know I can achieve this using trim and split. But just to make sure I pick up a right choice. What is the best way of achieving this?
Any help really appriciated.
i would not use string replace method in this case. Why?
e.g. :
string path = "C:\\Users1\\Users2\\Users122\\Users13\\Users133\\filename.xml";
path = path.Replace("\\TestResults", string.Empty);
// you will get "C:\Users222333\filename.xml"
that is not what you expected.
so how to fix this,
path = string.Join(Path.DirectorySeparatorChar.ToString(),
path.Split(Path.DirectorySeparatorChar).Where(x=> x!="Users1").ToArray()));
//C:\Users2\Users122\Users13\Users133\filename.xml
You can use String.Replace method like;
Returns a new string in which all occurrences of a specified Unicode
character or String in the current string are replaced with another
specified Unicode character or String.
string path = "C:\\Users\\dev\\Test\\TestResults\\Config\\Report.xml";
path = path.Replace("\\TestResults", string.Empty);
Console.WriteLine(path);
Output will be;
C:\Users\dev\Test\Config\Report.xml
Here a DEMO.

How to remove characters in a string?

How to remove the some characters in a string ..
string s="testpage\information.xml"
I need only information.xml how to do that?
System.IO.Path may help you with this since the string contains a file path information. In your case, you may use Path.GetFileName(string path) to get the file name from a string.
Example
string s = #"testpage\information.xml";
string filename = Path.GetFileName(s);
//MessageBox.Show(filename);
Thanks,
I hope you find this helpful :)
Assuming the value that will be in s is always a file path, use the Path class to extract the file name
var filename = Path.GetFileName(s);
File path is of the form
aaaa\bbb\ccc\dddd\information.xml
To retrieve the last string, you can divide your string using the delimiter \
String path = #"aaaa\bbb\ccc\dddd\information.xml";
String a[] = path.Split('\\');
This will give String array as ["aaaa", "bbb", "ccc", "dddd", "information.xml"]
You can retrieve the filename as
String filename = a[a.Length-1];
If it is going to be a file path, then you can use the System.IO.Path class (MSDN) to extract the filename.
string s = "testpage\information.xml"
var filename = Path.GetFilename(s);
If it's always right of the backslash separator then you can use:
if (s.Contains(#"\"))
s= s.Substring(s.IndexOf(#"\") + 1);
Hope this is what you want:
var result=s.Substring(s.LastIndexOf(#"\") + 1);
If you are using file paths, see the Path.GetFileName Method
It will not check whether the file exists or not. So it will be faster.
s = Path.GetFileName(s);
If you need to check whether file exists, use File.Exists class.
Another way is to use String.Split() method
string[] arr = s.Split('\\');
if(arr.Length > 0)
{
s = arr[arr.Length - 1];
}
Another way is to use RegEx
s = Regex.Match(s, #"[^\\]*$").Value;
You can use the following line of codes to get file extension.
string filePath = #"D:\Test\information.xml";
string extention = Path.GetExtension(filePath);
If you need file name alone use,
string filePath = #"D:\Test\information.xml";
string filename = Path.GetFilename(filePath );
Use string.Replcae
string s = #"testpage\information.xml";
s = s.Replace(#"testpage\\",""); // replace 'testpage\' with empty string
You will get Output => s=information.xml
# is need only because you have backslash in your string
For further reading about STRING REPLACE
http://www.dotnetperls.com/replace
http://msdn.microsoft.com/en-us/library/system.string.replace.aspx
In C++ you can do something like this. Basically search for "/" or "\" from right to left of the path and crop the string starting from the first occurance of the delimiter:
string ExtractFileName(const string& strPathFileName)
{
size_t npos;
string strOutput = strPathFileName;
if(strPathFileName.rfind(L'/', npos) || strPathFileName.rfind(L'\\', npos))
{
strOutput = strPathFileName.substr(npos+1);
}
return strOutput;
}

"The given path's format is not supported."

I have the following code in my web service:
string str_uploadpath = Server.MapPath("/UploadBucket/Raw/");
FileStream objfilestream = new FileStream(str_uploadpath +
fileName, FileMode.Create, FileAccess.ReadWrite);
Can someone help me resolve the issue with this error message from line 2 of the code.
The given path's format is not supported.
Permission on the folder is set to full access to everyone and it is the actual path to the folder.
The breakpoint gave me the value of str_uploadpath as C:\\webprojects\\webservices\\UploadBucket\\Raw\\.
What is wrong with this string?
Rather than using str_uploadpath + fileName, try using System.IO.Path.Combine instead:
Path.Combine(str_uploadpath, fileName);
which returns a string.
I see that the originator found out that the error occurred when trying to save the filename with an entire path. Actually it's enough to have a ":" in the file name to get this error. If there might be ":" in your file name (for instance if you have a date stamp in your file name) make sure you replace these with something else. I.e:
string fullFileName = fileName.Split('.')[0] + "(" + DateTime.Now.ToString().Replace(':', '-') + ")." + fileName.Split('.')[1];
For me the problem was an invisible to human eye "‪" Left-To-Right Embedding character.
It stuck at the beginning of the string (just before the 'D'), after I copy-pasted the path, from the windows file properties security tab.
var yourJson = System.IO.File.ReadAllText(#"D:\test\json.txt"); // Works
var yourJson = System.IO.File.ReadAllText(#"‪D:\test\json.txt"); // Error
So those, identical at first glance, two lines are actually different.
If you are trying to save a file to the file system. Path.Combine is not bullet proof as it won't help you if the file name contains invalid characters. Here is an extension method that strips out invalid characters from file names:
public static string ToSafeFileName(this string s)
{
return s
.Replace("\\", "")
.Replace("/", "")
.Replace("\"", "")
.Replace("*", "")
.Replace(":", "")
.Replace("?", "")
.Replace("<", "")
.Replace(">", "")
.Replace("|", "");
}
And the usage can be:
Path.Combine(str_uploadpath, fileName.ToSafeFileName());
Among other things that can cause this error:
You cannot have certain characters in the full PathFile string.
For example, these characters will crash the StreamWriter function:
"/"
":"
there may be other special characters that crash it too.
I found this happens when you try, for example, to put a DateTime stamp into a filename:
AppPath = Path.GetDirectoryName(giFileNames(0))
' AppPath is a valid path from system. (This was easy in VB6, just AppPath = App.Path & "\")
' AppPath must have "\" char at the end...
DateTime = DateAndTime.Now.ToString ' fails StreamWriter... has ":" characters
FileOut = "Data_Summary_" & DateTime & ".dat"
NewFileOutS = Path.Combine(AppPath, FileOut)
Using sw As StreamWriter = New StreamWriter(NewFileOutS , True) ' true to append
sw.WriteLine(NewFileOutS)
sw.Dispose()
End Using
One way to prevent this trouble is to replace problem characters in NewFileOutS with benign ones:
' clean the File output file string NewFileOutS so StreamWriter will work
NewFileOutS = NewFileOutS.Replace("/","-") ' replace / with -
NewFileOutS = NewFileOutS.Replace(":","-") ' replace : with -
' after cleaning the FileNamePath string NewFileOutS, StreamWriter will not throw an (Unhandled) exception.
Hope this saves someone some headaches...!
If you get this error in PowerShell, it's most likely because you're using Resolve-Path to resolve a remote path, e.g.
Resolve-Path \\server\share\path
In this case, Resolve-Path returns an object that, when converted to a string, doesn't return a valid path. It returns PowerShell's internal path:
> [string](Resolve-Path \\server\share\path)
Microsoft.PowerShell.Core\FileSystem::\\server\share\path
The solution is to use the ProviderPath property on the object returned by Resolve-Path:
> Resolve-Path \\server\share\path | Select-Object -ExpandProperty PRoviderPath
\\server\share\path
> (Resolve-Path \\server\share\path).ProviderPath
\\server\share\path
Try changing:
Server.MapPath("/UploadBucket/Raw/")
to
Server.MapPath(#"\UploadBucket\Raw\")
This was my problem, which may help someone else -- although it wasn't the OP's issue:
DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.ToString());
I determined the problem by outputting my path to a log file, and finding it not formatting correctly. Correct for me was quite simply:
DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.FullName.ToString());
Does using the Path.Combine method help? It's a safer way for joining file paths together. It could be that it's having problems joining the paths together
I had the same issue today.
The file I was trying to load into my code was open for editing in Excel.
After closing Excel, the code began to work!
I am using the (limited) Expression builder for a Variable for use in a simple File System Task to make an archive of a file in SSIS.
This is my quick and dirty hack to remove the colons to stop the error:
#[User::LocalFile] + "-" + REPLACE((DT_STR, 30, 1252) GETDATE(), ":", "-") + ".xml"
Image img = Image.FromFile(System.IO.Path.GetFullPath("C:\\ File Address"));
you need getfullpath by pointed class. I had same error and fixed...
If the value is a file url like file://C:/whatever, use the Uri class to translate to a regular filename:
var localPath = (new Uri(urlStylePath)).AbsolutePath
In general, using the provided API is best practice.

Categories

Resources