I would like to give a document I've created programmatically a name which contains the returned value of DateTime.Now.ToString();
The trial failed when ":" symbol is a content of the file name.
Any Idea?
Avoid problemw with culture like this
DateTime.Now.ToString("yyyy-MMdd-HH-mm", CultureInfo.InvariantCulture)
also you can try out
string n = string.Format("typeoffile-{0:yyyy-MM-dd_hh-mm-ss-tt}.ext",
DateTime.Now);
try this will work for you
String.Replace(".","_")
turn in
DateTime.Now.ToString().Replace(".","_")
I would specify a format for DateTime.ToString(), for example:
DateTime.Now.ToString("yyyyMMddhhmmss") //results in "20131127103249"
If you want to go the String.Replace route, I suggest leveraging a useful method called Path.GetInvalidFileNameChars():
string s = DateTime.Now.ToString();
foreach (char c in Path.GetInvalidFileNameChars()) // replace all invalid characters with an underscore
{
s = s.Replace(c, '_');
}
Or, if you're into the whole brevity thing, you can do the same thing in a one-liner using LINQ:
var s = new String(DateTime.Now.ToString().Select(ch => Path.GetInvalidFileNameChars().Any(invalid => invalid == ch) ? '_' : ch).ToArray());
You can use the replace function to replace the : with for example _
DateTime.Now.ToString().Replace(":","_");
Why don't you try removing the ":" symbol, i.e. filename will be:
20131127_0530
DateTime.Now.ToString("yyyyddMM_HHmm")
you should be using the custom ToString method specify a formatter i.e:
DateTime.Now.ToString("ddMMyyyy") - shows daymonthyear
Related
I am saving a file name with a string value plus the date as follows:
var fileName = String.Format("{0}_{1}.zip", "fileName", DateTime.Now.ToString("yyyy-MM-dd"));
The above line gives me:
fileName_2015-11-24.zip
Is it some how possible that I can get fileName_2015_11_24.zip
I have actually tried with DateTime.Now.ToString("yyyy_MM_dd") But I forgot to mention in my question.
One possibility is to replace dashed - with underscores _ but is there any other solution ?
Thanks.
How about this?
String.Format("{0}_{1:yyyy_MM_dd}", "filename", DateTime.Now);
To clarify: You can use DateTime format parameters in String.Format itself.
Have you tried simply using underscores in your date format string?
DateTime.Now.ToString("yyyy_MM_dd")
Just replace - with _
var fileName = String.Format("fileName_{0}.zip", DateTime.Now.ToString("yyyy_MM_dd"));
You can provide formatting parameters for each value in your call to String.Format. Just add a custom formatting string after a colon (:), like this:
var fileName = String.Format("fileName_{0:yyyy_MM_dd}.zip", DateTime.Now);
You could do this
$"FileName_{DateTime.Now:MM_dd_yyyy}";
I have a webmethod and get my queryString with this code:
string name = "";
int pos7 = context.Request.UrlReferrer.PathAndQuery.IndexOf("name");
if (pos7 >= 0)
name = context.Request.UrlReferrer.PathAndQuery.Substring(pos7 + 5);
The problem is the adresse "www.test.com?name=tiki song" will be end up in "tiki%20song" on my string.
How to avoid that?
(Yes I could replace the %20 to " " but there are a lot of more of that kind, right?"
Consider using Uri.UnescapeDataString
http://msdn.microsoft.com/en-us/library/system.uri.unescapedatastring.aspx
As per this previous you could create a URI and extract it using "UnescapeDataString" (post). Referencing this MSDN page.
Or alternatively, you can use some of the HtmlDecode methods as MikeBarkemeyer had mentioned in the comments.
So I have a few file extensions in my C# projects and I need to remove them from the file name if they are there.
So far I know I can check if a Sub-string is in a File Name.
if (stringValue.Contains(anotherStringValue))
{
// Do Something //
}
So if say stringValue is test.asm, and then it contains .asm, I want to somehow remove the .asm from stringValue.
How can I do this?
if you want a "blacklist" approach coupled with the Path library:
// list of extensions you want removed
String[] badExtensions = new[]{ ".asm" };
// original filename
String filename = "test.asm";
// test if the filename has a bad extension
if (badExtensions.Contains(Path.GetExtension(filename).ToLower())){
// it does, so remove it
filename = Path.GetFileNameWithoutExtension(filename);
}
examples processed:
test.asm = test
image.jpg = image.jpg
foo.asm.cs = foo.asm.cs <-- Note: .Contains() & .Replace() would fail
You can use Path.GetFileNameWithoutExtension(filepath) to do it.
if (Path.GetExtension(stringValue) == anotherStringValue)
{
stringValue = Path.GetFileNameWithoutExtension(stringValue);
}
No need for the if(), just use :
stringValue = stringValue.Replace(anotherStringValue,"");
if anotherStringValue is not found within stringValue, then no changes will occur.
One more one-liner approach to getting rid of only the ".asm" at the end and not any "asm" in the middle of the string:
stringValue = System.Text.RegularExpressions.Regex.Replace(stringValue,".asm$","");
The "$" matches the end of the string.
To match ".asm" or ".ASM" or any equivlanet, you can further specify Regex.Replace to ignore case:
using System.Text.RegularExpresions;
...
stringValue = Regex.Replace(stringValue,".asm$","",RegexOptions.IgnoreCase);
I'm developing a piece of software in C# and the end result is an Excel spreadsheet. The title of the spreadsheet is created using several variables to explain exactly what the spreadsheet is. One of the variables is a string which contains data like this:
'1.1.1'
I need to convert it at the point of creating the spreadsheet to be:
'1_1_1'
I have tried using the String.Replace method but it just seems to ignore it. Any ideas?
Best Regards
I bet you doing this:
myString.Replace(".","_");
When you should be doing this:
myString = myString.Replace(".","_");
Remember, in .Net strings are immutable, so any changes result in a new string.
Chances are you're ignoring the result of string.Replace. You need:
text = text.Replace('.', '_');
Just calling Replace doesn't change the existing string - it creates a new string and returns it. Strings are immutable in .NET - they never change after creation.
When you use string.Replace are you remembering that you have to assign it?
yourString.Replace(".", "_");
Will do nothing.
string newString = yourString.Replace(".", "_");
will return the string with the dots replaced with underscores.
If I had to guess, you're not capturing the value returned by String.Replace. Strings are immutable, so String.Replace returns a new string, which you need to store a reference to.
string foo = "1.1.1";
foo = foo.Replace('.', '_');
String input = "1.1.1";
input = input.Replace(".", "_");
strings are immutable, so make sure you're using it like this:
string myString = "1.1.1";
myString = myString.Replace('.', '_');
String.Replace is the right way to do this:
private void button1_Click(object sender, RoutedEventArgs e) {
String myNumbers = "1.1.1";
Console.WriteLine("after replace: " + myNumbers);
myNumbers = myNumbers.Replace(".", "_");
Console.WriteLine("after replace: " + myNumbers);
}
will produce:
after replace: 1.1.1
after replace: 1_1_1
Look at this statement :
messageBox.show( System.Security.Principal.WindowsIdentity.GetCurrent().Name);
the output of this statement is :
Roshan\mohdibrahim.tasal
but i want to display me only :
mohdibrhaim.tasal
how can i do this?
You can just split the name on the "\" and retrieve the 2nd item.
e.g.
System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\')[1]
Edit:
You'll want to make this safe by first checking for the existence of a backslash - if there isn't one, you just want to take the Name as-is.
Why don't you trim returned value until '\' is reached,
following code does the trick
WindowsIdentity current = System.Security.Principal.WindowsIdentity.GetCurrent();
if(current!=null)
{
string name = current.Name;
string value = name.Substring(name.IndexOf('\\') + 1);
}
Environment.UserName should work without any splitting or additional logic.