How to add '/' between two strings? - c#

I have the following code:
if (!string.IsNullOrEmpty(_location.FolderName))
{
name = _location.FolderName + '/' + name;
}
Is it correct way to add / between two strings? Or I should use the following code:
if (!string.IsNullOrEmpty(_location.FolderName))
{
name = _location.FolderName + "/" + name;
}

For concatenating file paths, you should use the System.IO.Path.Combine method instead.
using System.IO;
...
if (!string.IsNullOrEmpty(_location.FolderName))
{
name = Path.Combine(_location.FolderName, name);
}
One thing to note, as Anton mentioned in the comments below is that you must ensure that the characters in the paths are valid, you can find more information in the documentation.

Use Path.DirectorySeparatorChar for this purpose: https://msdn.microsoft.com/ru-ru/library/system.io.path.pathseparator%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
Console.WriteLine("Path.AltDirectorySeparatorChar={0}", Path.AltDirectorySeparatorChar);
Console.WriteLine("Path.DirectorySeparatorChar={0}", Path.DirectorySeparatorChar);
Console.WriteLine("Path.PathSeparator={0}", Path.PathSeparator);
Console.WriteLine("Path.VolumeSeparatorChar={0}", Path.VolumeSeparatorChar);
Console.Write("Path.GetInvalidPathChars()=");
foreach (char c in Path.GetInvalidPathChars())
Console.Write(c);
Console.WriteLine();
Will give result:
// Path.AltDirectorySeparatorChar=/
// Path.DirectorySeparatorChar=\
// Path.PathSeparator=;
// Path.VolumeSeparatorChar=:

Use double back slash it will help
if (!string.IsNullOrEmpty(_location.FolderName))
{
name = _location.FolderName + "\\" + name;
}

Related

How can I insert a word at the first space in a line in c#?

I have a string like following,
string myline="public methodname(parameters)";
How can I insert a new string, like "static" at the first occurence space, that is between public and methodname.
Note that the first word and second word of my string can be anything. And I want to insert a string at the first space in my string.
so my output will be like
public static methodname(parameters)
I have used, Insert and IndexOf methods. But I cannot get the exact result. Please help. Thanks in Advance
Here you go
string myline = "public methodname(parameters)";
string result = myline.Insert(myline.IndexOf(' '), " static");
Or you can try Replace
string myline = "public methodname(parameters)";
string result = myline.Replace("public ", "public static ")
.NET Fiddle
Example:
string s = "Dot Net ";
string v = s.Replace("Net", "Basket");
Something like this, I haven't tested previous version of the code, follow should be OK.
String myline = "Public something";
int pos = myline.IndexOf(" ");
if(pos < 0)
{
//Error
}
String stringYouWant = myline.Substring(0, pos) + " static " + myline.Substring(pos +1);
Console.WriteLine(stringYouWant);

Convert unformatted string (not valid json) to json

I have a string which I get from a webservice which looks like this:
({
id=1;
name="myName";
position="5";
})
which is not a parsable json. I wanted to ask if there are any ways besides going character to character and correcting them to convert such string into a parsable json like this:
{
"id":1,
"name":"myName",
"position":"5"
}
Check this link it will be helpful :
https://forum.unity3d.com/threads/json-web-services.366073/
You cold run a bunch of regex replaces for each change. But you'll need captures for the property names etc The performance will be horrible.
If the format is known and reliable (eg what happens with collections/arrays and sub-objects). And the service provider does not provide a client or SDK. Then your best bet is to write your own parser. It's not that hard to create your own from scratch. Or you can use a parser library like Irony.net or eto.parse. Both of these allow you to construct a grammar in c# so it is fully self contained without the need for compiler-compilers and generated code. There is also a class of parser called "monadic" parsers like Sprache which are of a simpler nature (once you wrap your head around them).
Whichever approach is taken you'll end up with a way of recognising each property and object boundary where you can do what you need to do: set a property; create a JToken; whatever...
Then you can wrap the whole lot in a MediaTypeFormatter and call the service via HttpClient and get objects out.
Finally I had to write my own function to convert it to a parsable json, here's the function I wrote:
public string convertToJson(string mJson)
{
mJson = mJson.Replace("(","[");
mJson = mJson.Replace(")","]");
string mJson2 = mJson.Trim('[',']');
string[] modules = mJson2.Split(',');
for(int i = 0;i<modules.Length;i++)
{
Debug.Log("module["+i+"]: " + modules[i]);
}
for(int m=0;m<modules.Length;m++)
{
char[] mCharacter = {'{','}'};
modules[m] = modules[m].Replace("{",string.Empty).Replace("}",string.Empty).Trim();
Debug.Log("module["+m+"] after trim: " + modules[m]);
string[] items = modules[m].TrimEnd(';').Split(';');
modules[m] = "{";
for(int j=0;j<items.Length;j++)
{
Debug.Log("item["+j+"]: " + items[j]);
string[] keyValue = items[j].Split('=');
Debug.Log("key,value: " + keyValue[0] + ", " + keyValue[1]);
modules[m] = modules[m] + "\"" + keyValue[0].Trim() + "\":" + keyValue[1].Trim() + ",";
}
modules[m] = modules[m].Substring(0,modules[m].Length-1) + "}";
Debug.Log("modules["+m+"] final: " + modules[m]);
}
string finalJson = "[";
for(int m=0;m<modules.Length;m++)
{
finalJson = finalJson + modules[m] + ",";
}
finalJson = finalJson.Substring(0,finalJson.Length-1) + "]";
Debug.Log("finalJson: " + finalJson);
return finalJson;
}

Get page name from URI, substring between two characters

I want to get the page name from a URI for instance if I have
"/Pages/Alarm/AlarmClockPage.xaml"
I want to get AlarmClockPage
I tried
//usage GetSubstring("/", ".", "/Pages/Alarm/AlarmClockPage.xaml")
public static string GetSubstring(string a, string b, string c)
{
string str = c.Substring((c.IndexOf(a) + a.Length),
(c.IndexOf(b) - c.IndexOf(a) - a.Length));
return str;
}
But because the string being search may contain one or more forward slashes, I don't think this method work in such case.
So how do I consider the multiple forward slashes that may present?
Why don't you use method which is already in the framework?
System.IO.Path.GetFileNameWithoutExtension(#"/Pages/Alarm/AlarmClockPage.xaml");
If you only want to use string functions, you may try:
var startIdx = pathString.LastIndexOf(#"/");
var endIdx = pathString.LastIndexOf(".");
if(endIdx!=-1)
{
fileName = pathString.Substring(startIdx,endIdx);
}
else
{
fileName = pathString.Substring(startIdx);
}
It gives file name from a given file path. try this
string pageName = System.IO.Path.GetFileName(#"/Pages/Alarm/AlarmClockPage.xaml");

How to make filenames web safe using c#

This is not about encoding URLs its more to do with a problem I noticed where you can have a valid filename on IIS sucha as "test & test.jpg" but this cannot be downloaded due to the & causing an error. There are other characters that do this also that are valid in windows but not for web.
My quick solution is to change the filename before saving using a regex below...
public static string MakeFileNameWebSafe(string fileNameIn)
{
string pattern = #"[^A-Za-z0-9. ]";
string safeFilename = System.Text.RegularExpressions.Regex.Replace(fileNameIn, pattern, string.Empty);
if (safeFilename.StartsWith(".")) safeFilename = "noname" + safeFilename;
return safeFilename;
}
but I was wondering if there were any better built in ways of doing this.
Built-in I don't know about.
What you can do is, like you say, scan the original filename and generate a Web-safe version of it.
For such Web-safe versions, you can make it appear like slugs in blogs and blog categories (these are search engine-optimized):
Only lowercase characters
Numbers are allowed
Dashes are allowed
Spaces are replaced by dashes
Nothing else is allowed
Possibly you could replace "&" by "-and-"
So "test & test.jpg" would translate to "test-and-test.jpg".
Just looking back at this question since its fairly popular. Just though I would post my current solution up here with various overloads for anyone who wants it..
public static string MakeSafeFilename(string filename, string spaceReplace)
{
return MakeSafeFilename(filename, spaceReplace, false, false);
}
public static string MakeSafeUrlSegment(string text)
{
return MakeSafeUrlSegment(text, "-");
}
public static string MakeSafeUrlSegment(string text, string spaceReplace)
{
return MakeSafeFilename(text, spaceReplace, false, true);
}
public static string MakeSafeFilename(string filename, string spaceReplace, bool htmlDecode, bool forUrlSegment)
{
if (htmlDecode)
filename = HttpUtility.HtmlDecode(filename);
string pattern = forUrlSegment ? #"[^A-Za-z0-9_\- ]" : #"[^A-Za-z0-9._\- ]";
string safeFilename = Regex.Replace(filename, pattern, string.Empty);
safeFilename = safeFilename.Replace(" ", spaceReplace);
return safeFilename;
}
I think you are referring to the "A potentially dangerous Request.Path value was detected from the client (%)" error which Asp.Net throws for paths which include characters which might indicate cross site scripting attempts:
there is a good article on how to work around this:
http://www.hanselman.com/blog/ExperimentsInWackinessAllowingPercentsAnglebracketsAndOtherNaughtyThingsInTheASPNETIISRequestURL.aspx
Here's the one I use:
public static string MakeFileNameWebSafe(string path, string replace, string other)
{
var folder = System.IO.Path.GetDirectoryName(path);
var name = System.IO.Path.GetFileNameWithoutExtension(path);
var ext = System.IO.Path.GetExtension(path);
if (name == null) return path;
var allowed = #"a-zA-Z0-9" + replace + (other ?? string.Empty);
name = System.Text.RegularExpressions.Regex.Replace(name.Trim(), #"[^" + allowed + "]", replace);
name = System.Text.RegularExpressions.Regex.Replace(name, #"[" + replace + "]+", replace);
if (name.EndsWith(replace)) name = name.Substring(0, name.Length - 1);
return folder + name + ext;
}
If you are not concerned to keep the original name perhaps you could just replace the name with a guid?

Newline char in exchange appointments

I need to put an adress into a appointment. The address is constructed out of several variables. Of course I also need some newlines. But "\n" doesnt result in an new line when i open the appointment in outlook.
Ok here is code snippet:
string address = name + "\n" + strasse + "\n" + plz.ToString() + " " + ort;
if ( telefon != "") {
address = address + "\nTelefon:: " + telefon;
}
if ( natel != "") {
address = address + "\nNatel: " + natel;
}
if ( mail != "") {
address = address + "\nE-Mail: " +mail;
}
Nothing special. The Problem is when i write this to the body of an appointment, then there aren't any actual newlines.
Its pretty hard to diagnose this without seeing at least an example of the string you are passing, but one thing that I tend to do in my C# code is to use the constant:
Environment.NewLine
Or I use the StringBuilder class with the AppendLine() call to add a newline.
Edit: Based on your code snippet, I would write it this way (it will be more performant as well). With your snippet, lots of strings are being allocated (because strings are immutable). The recommended approach in this case is to use StringBuilder.
StringBuilder address = new StringBuilder();
address.AppendLine(name);
address.AppendLine(strasse);
address.Append(plz.ToString()); // This may not be neccessary depending on the type of plz, StringBuilder has overloads that will convert base types to string for you
address.Append(" ");
address.Append(ort);
if (!string.IsNullOrEmpty(telefon))
{
address.AppendLine();
address.Append("Telefon:: ");
address.Append(telefon);
}
if (!string.IsNullOfEmpty(natel))
{
address.AppendLine();
address.Append("Natel: ");
address.Append(natel);
}
if (!string.IsNullOrEmpty(mail))
{
address.AppendLine();
address.Append("E-Mail: ");
address.Append(mail);
}
return address.ToString();
Note: If you are using .Net 4.0 you can use string.IsNullOrWhitespace instead of IsNullOrEmpty to check for not just an empty string, but one that contains only whitespace.
Edit 2 - Based on your answer of needing <br /> tags instead of newlines.
const string newLine = " <br /> ";
StringBuilder address = new StringBuilder();
address.Append(name);
address.Append(newLine);
address.Append(strasse);
address.Append(newLine);
address.Append(plz.ToString()); // This may not be neccessary depending on the type of plz, StringBuilder has overloads that will convert base types to string for you
address.Append(" ");
address.Append(ort);
if (!string.IsNullOrEmpty(telefon))
{
address.Append(newLine);
address.Append("Telefon:: ");
address.Append(telefon);
}
if (!string.IsNullOfEmpty(natel))
{
address.Append(newLine);
address.Append("Natel: ");
address.Append(natel);
}
if (!string.IsNullOrEmpty(mail))
{
address.Append(newLine);
address.Append("E-Mail: ");
address.Append(mail);
}
return address.ToString();
Ok i got it now. I found out that appointments are stored in html format.
So i tried to use the html entity for \r\n, .That didn't work. I finally solved the problem by using the br tag
While you're absolutely correct about using <br/>, newline is not the only thing Exchange eats in notes/appointment body.
I ended up with the following code:
Regex NewlineRegex = new Regex("(\r\n)|(\r)|(\n)");
string valueToWrite = NewlineRegex.Replace(
SecurityElement.Escape(fieldValue), "<br/>")
.Replace(" ", " ")
.Replace("&apos;", "'"); // &apos; is not in HTML.
And even after that you will read back an extra "\r\n" in the end of the body/notes, so I have to .TrimEnd() them after reading.
you should try "\r\n"
See http://www.infinitec.de/post/2009/08/25/Exchange-WebServices-Bug-with-Lineendings.aspx

Categories