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}";
Related
This question already has answers here:
C# DateTime to "YYYYMMDDHHMMSS" format
(18 answers)
Closed 5 years ago.
I developing a xamarin form app and I am assigning the current date time as a Filename for image. Currently the image is saved as "7202017 53150 PM.jpg". I want it to be saved like this "720201753150PM.jpg". How can I remove the space between the date and time?
I tried like below but it did not work.
string _imagename = DateTime.Now.ToString();
_imagename.Replace(" ", string.Empty);
Actually the String.Replace() Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string(in short it won't change the actual string) So you need to assign the result to another variable. And perform the replace operation there.
But Why you go for another replace? whynot use .ToString() like the following?
string format = "Mddyyyyhhmmsstt";
string _imagename = String.Format("{0}.jpg",DateTime.Now.ToString(format))
You need to assign the new value as string is immutable:
string _imagename = DateTime.Now.ToString();
_imagename = _imagename.Replace(" ", string.Empty);
This is fastest way I know:
Regex.Replace(_imagename, #"\s+", "")
Looking at your string ill also suggest replace spaces with a empty string. And you could do it by applying built in Replace method:
string _imagename = DateTime.Now.ToString();
_imagename = _imagename.Replace(" ", string.Empty);
If you want to order by file name I'd suggest to use a notation like yyyyMMddHHmmss. That way, with increasing date/time the sort order will also increase.
Other than that, strings are immutable in c#. Thus calling Replace does not change the original string. You need to assign the result to your variable as #Romano Zumbé pointed out.
You can just use a format string like the following (including the sorting suggestion):
string imagename = $"{DateTime.Now:yyyyMMddHHmmss}.jpg";
otherwise it would be:
string imagename = $"{DateTime.Now:Mddyyyyhmmsstt}.jpg";
I have looked around for this, but I'm not sure it's possible with string interpolation (I'm using VS2015).
string sequenceNumber = $"{fieldValuePrefix.ToUpper()}{separator}{similarPrefixes + 1:D4}";
Is there any way to make D4 a variable ? Some say yes, some no. Apparently, VS2015 C#6.0 is able to do it.
This works, it will return a string like WMT-0021, depending on fieldValuePrefix (WMT), separator (-) and the value of similarPrefixes (20). But I'd like the "D4" part to be a method argument instead of hardcoded in there.
Any ideas ?
You can, but you have to use explicit ToString call like this:
string format = "D4";
string sequenceNumber =
$"{fieldValuePrefix.ToUpper()}{separator}{(similarPrefixes + 1).ToString(format)}";
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
I have the following data:
D:\toto\food\Cloture_49000ert1_10_01_2013.pdf
D:\toto\food\Cloture_856589_12_01_2013.pdf
D:\toto\food\Cloture_66rr5254_10_12_2012.pdf
How can I extract the date part?
For example:
D:\toto\food\Cloture_49000ert1_10_01_2013.pdf --> 10_01_2013
D:\toto\food\Cloture_856589_12_01_2013.pdf --> 12_01_2013
D:\toto\food\Cloture_66rr5254_10_12_2012.pdf --> 10_12_2012
My idea is to use LastIndexOf(".pdf") and then count 10 character backwards.
How can I solve this using substrings or another method?
Use Substring in this case.
Retrieves a substring from this instance. The substring starts at a
specified character position.
Try like this;
string s = "D:\\toto\\food\\Cloture_490001_10_01_2013.pdf";
string newstring = s.Substring(s.Length - 14, 10);
Console.WriteLine(newstring);
Here is a DEMO.
You do not need to find index of .pdf
path.Substring(path.Length - 14, 10)
I'd do this with a Regex.
^[\w:\\]+cloture_(\d+)_([\d_]+).pdf$
Would match the date in the second group.
If the filename is always in that format, you could do something crude like this:
string filename = #"D:\toto\food\Cloture_490001_10_01_2013.pdf";
string date = filename.Substring(filename.Length - 14, 10);
That will get a substring from 10_01_2013.pdf, which is 14 characters long, but only take the first 10 characters, leaving you with 10_01_2013.
If, however, the filename is in a different format and the date could appear anywhere within the name, you may want to consider something like Regular Expressions to be able to do a match for ##_##_#### and pull that out.
try this approach:
string dateString = textString.Substring(textString.Length-14, 10);
see here as well: Extract only right most n letters from a string
If you want to use LastIndexOf then
string str = #"D:\toto\food\Cloture_490001_10_01_2013.pdf";
string temp = str.Substring(str.LastIndexOf(".pdf") - 10, 10);
And you can parse it like
DateTime dt;
if(DateTime.TryParseExact(temp, "MM_dd_yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//valid
}
else
{
//invalid
}
I'd go with your idea of using LastIndexOf ".pdf" and then count backwards. Or use the Path.GetFileNameWithoutExtension method to just get the name and then take the last 10 characters.
These methods will both keep working if the path to the filenames ever changes (which it probably will) and don't rely on magic numbers (other than the one that defines the length of the substring we are interested in) to find the right place in the string.
I think this should be a pretty easy question to answer but I can't seem to figure it out.
I am adding text to labels from a sqldatasource in c#. All of that works, but I want to be able to format the text. I want to 1) be able to change the format to 0.00 (instead of a string of decimals) and I would also like to be able to add words before the text. I assume I need to somehow use the string.format command but can't figure out how to work it in. Any help would be greatly appreciated. Here's my code below:
DataView dvSql = (DataView)DeskSummary.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drvSql in dvSql)
{
Desk.Text = drvSql["Deskname"].ToString();
MarginLabel.Text = drvSql["margin"].ToString();
CurrentCI.Text = drvSql["comp_index_primarycomp"].ToString();
WalMartCurrentCI.Text = drvSql["comp_index_walmart"].ToString();
ForecastMargin.Text = drvSql["margin_forecast"].ToString();
WalMartForecastCI.Text = drvSql["comp_index_walmart_forecast"].ToString();
ForecastCI.Text = drvSql["comp_index_primarycomp_forecast"].ToString();
}
You can pass the format argument to the ToString() method like so:
MarginLabel.Text = drvSql["margin"].ToString("0.00");
However, as you said you wanted to prepend some text. Therefore, I recommend:
MarginLabel.Text = String.Format("Prepended text {0:0.00}", drvSql["margin"]);
Note: I just picked one of your labels; I'm not sure which ones get special formatting treatment.
use the
string.Format("This is a before text {"0"},your param)
// you can add as many variables and {""} string literals as you need just make sure that you separate the variables with a ","
Here is the code
string stringNumber = "5123.34214513";
decimal decimalNumber = Decimal.Parse(stringNumber);
string output = String.Format("Your text: {0:0.00}", decimalNumber);
Console.WriteLine(output); //Your text: 5123.34
This works if the column is of type string
String.Format() will do what you need for prepending/appending text values,
string.Format("prepend text {"0"} append text", paramString)
But if you want to actually format the value you are getting back from SQL, then you would need to use String.Format() on that value as well as possibly some RegEx expressions and/or .ToUpperCase or .ToLowercase for your capitalization... something like.
var capitalizedString = paramString.subStr(0,1).ToUppercase + paramString.subStr(1, paramstring.Length);
string.Format("Prepended text {"0"} plus appended text", capitalizedString);