DateTime as file name - c#

I need to create some log files with a name like this:
HH:mm_dd-MM-yyyy.log
I've tried to convert DateTime & DateTime.Now like this but the compiler encounters the next error:
The given path's format is not supported.
Code i've tried:
#1
var currentDateTime = DateTime.Now;
string format = "HH:mm_dd-MM-yyyy";
string datetime = currentDateTime.ToString(format);
File.Create("Log/GameLog/"+datetime+".log");
#2
string datetime = DateTime.Now.ToString("HH:mm_dd-MM-yyyy");
File.Create("Log/GameLog/"+datetime+".log");
In this couple of cases the same error was raised by the compiler...
So in the end, my question is, how can i use datetime as a file name?

The problem is the : character, you can't use that in a file name
DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");

Widows Operating System does not allow following special characters in filename.
/ \ : * ? " < > |
so you need to Replace colon : with some other character (either with _ or with -)
Try This:
string datetime = DateTime.Now.ToString("HH_mm_dd-MM-yyyy");

try removing some of the characters you are returning with format and then add them in on at a time to see which is causing the problem.
My guess is it maybe the : character causing you a problem
also check this post which may help.
How to remove illegal characters from path and filenames?
regards

Related

C# String format: escape a dot

I have a line of code, something like:
mbar.HealthLabel.text = String.Format("{0:0.0}", _hp);
Output is: 2.25 for example. Is it possible to escape a dot from the output string view with String.Format function ?
For. ex. 225,
To make my question more clear, I need the same effect like:
Math.Floor(_hp * 100).ToString();
But need to do it by String.Format template.. Thanks.
Simply you can do it this way
double value = 1.25;
var stringValue = string.Format("{0:0}", value * 100, CultureInfo.InvariantCulture); //125
EDIT:
More general solution would be to Replace the dot with empty string as stated in the comments.
double value = 1.25;
var stringValue = value.ToString(CultureInfo.InvariantCulture).Replace(".",string.Empty);
EDIT2: Also there is another general idea that do not use Replace function (but also it does not use the String.Format)
var stringValue = string.Join("", value.ToString().Where(char.IsDigit));
Also another similar idea:
var stringValue = new string(value.ToString().Where(char.IsDigit).ToArray());
First of all, please read my comment to the question. As i mentioned there, string format for numeric values depends on regional settings. So, below line
mbar.HealthLabel.text = String.Format("{0:0.0}", _hp);
will return: 2,25 (as to the polish numeric standard)
In my opinion you need something like this:
mbar.HealthLabel.text = String.Format("{0:D}", Math.Floor(_hp*100));
For furhter details, please see:
Standard Numeric Format Strings
Custom Numeric Format Strings
Up to Microsoft.NET Framework 4.7 there is no way to solve this when we are only allowed to modify the format string ("template"). All solutions require to either:
Post-process the resulting string. Here, the closest for the special case with two decimals may be the % format
Compute the numeric argument first to make it integer
Write and apply a custom IFormatProvider implementation
If you want to eliminate the decimal separtor ("escape the dot", as you've put it), try replacing the decimal separator with empty string:
string result = String
.Format("{0:0.0}", _hp)
.Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, "");

Varying filepaths in C#

I am creating C# Windows Form that retrieves files from shared drives as email attachments. I am trying to automate the file retrieval process, but the filepaths available to me vary according to the date. For example:
V:\....\Dec-03\filename12-3-2013.xml
J:\.....\December\filename12-4-2013
I have the filepath stored as string from a textbox, but since the path varies slightly day-to-day, I've been trying to figure out how automate this process. In the past I've used VBA code where I've concatenated method calls into the string like this
"..." & Day(Date) & "..."
(I replaced the ampersand with the plus sign of course for C#)
But this just gets me an illegal characters in path Argument exception.
I am using a check for filedate and taking a a specific filepath through a textbox. I want particular files that are being updated in monthly folders and the filename contains a date. I want to grab the ones with today's date or yesterday's date, but some have no date in the filename or directory at all. Since there isn't a lot of consistency, I would love to enter code
"+ DateTime.Now.ToString() +"
in the textbox per individual filepath as I load them via the form and have the program execute like I've done with some VBA code, but I get Illegal characters with the double quotes in the middle of a filepath. Is there some work around or will I need to create fixes for every particular pattern?
Use System.IO.Path.Combine(...) to handle chaining directories together (it takes care of extra slashes for you). In your combine, use String.Format(SomeFormatString, token1value, toke2value, etc.) to give you the name you were wanting.
C# uses + to append strings instead of & in older VB.
"My Date: " + DateTime.Now.ToString("MM/dd/yyyy")
An example of this with the String.Format I showed above would be
string.Format("My Date: {0}", DateTime.Now.ToString("MM/dd/yyyy"))
If I'm following what you're saying about Day(Date), you might try some thing like this in C#:
MyObject.SomeMethod("some string " + dateValue.ToString("ddd") + " more string data");
Where dateValue is a DateTime object and the "ddd" parameter tells the ToString method to return a three character abbreviation of the day of the week (e.g. 'Wed').
For more information on using ToString with DateTime objects to extract various parts of the date, see
http://msdn.microsoft.com/en-us/library/bb762911(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
The ToString overload of the DateTime structure will allow you to format a date as the Month name, etc.
var x = DateTime.Today.ToString("MMMM"); // December
You can include other characters in the format string as well, for example to get Dec-19 you can use:
var x = DateTime.Today.ToString("MMM-dd"); // Dec-19
TyCobb's answer covers combining the formatted date into a path using Path.Combine (which I generally recommend).
You can also use String.Format to insert a formatted value into a string, which is often easier to read and leads to fewer mistakes. For example, to generate your first example, you could use the following:
var path =
String.Format("V:....\{0:MMM-dd}\filename{0:M-d-yyyy}.xml", DateTime.Today);

what is the best way to parse out string from longer string?

i have a string that looks like this:
"/dir/location/test-load-ABCD.p"
and i need to parse out "ABCD" (where ABCD will be a different value every day)
The only things that i know that will always be consistent (to use for the logic for parsing) are:
There will always be be a ".p" after the value
There will always be a "test-load-" before the value.
The things i thought of was somehow grab everything past the last "/" and then remove the last 2 characters (to take case of the ".p" and then to do a
.Replace("test-load-", "")
but it felt kind of hacky so i wanted to see if people had any suggestions on a more elegant solution.
You can use a regex:
static readonly Regex parser = new Regex(#"/test-load-(.+)\.p");
string part = parser.Match(str).Groups[1].Value;
For added resilience, replace .+ with a character class containing only the characters that can appear in that part.
Bonus:
You probably next want
DateTime date = DateTime.ParseExact(part, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Since this is a file name, use the file name parsing facility offered by the framework:
var fileName = System.IO.Path.GetFileNameWithoutExtension("/dir/location/test-load-ABCD.p");
string result = fileName.Replace("test-load-", "");
A “less hacky” solution than using Replace would be the use of regular expressions to capture the solution but I think this would be overkill in this case.
string input = "/dir/location/test-load-ABCD.p";
Regex.Match(input, #"test-load-([a-zA-Z]+)\.p$").Groups[1].Value

Saving formatted timestring as file name problem in c#

HI guys,
I only started c# recently so I'm not 100% familiar with it's syntax yet and I got into a problem. I'd like to write the current time into a filename. I'm using the following code:
DateTime now = DateTime.now;
string dateString = string.Format(#"Z:\test\{0}.bmp",now.ToString("s"));
bitmap.Save(dateString);
Now this gives me a can't access filepath error. Apparently it has something to do with the ":" characters at the time part (at least when I give a now.ToString("d") ) it saves fine.
Any idea whats causing this? Thanks.
The "s" format will create a filename of something like:
2009-06-15T13:45:30.bmp
That's just not a valid filename, due to the colon. Either replace the colon with another character after calling ToString, or use a different format.
Note that "d" won't always work either, as it can include "/" in the name, depending on the culture.
Personally I'd suggest something like "yyyyMMdd-HHmmss" which will give you something like
20090615-134530.bmp
Regardless of the code, the Windows filesystems won't allow the use of a colon (or several other "special" characters) in a filename. So the issue is happening at the OS level, not in your code.
You'll want to strip out those characters and/or format the timestamp differently to use it as a filename.
Some characters are not valid in filenames on Windows - See this link. This is not related to c#.
That is caused by the Windows file system, which disallows :'s in file names.
':' are invalid characters for naming a file. You'll need to determine some other valid character to substitute for ':' before attempting to save the file.
public static class SPStringUtils
{
public static string MakeFilename(this DateTime dt)
{
return dt.ToString("yyyyMMdd-HHmmss");
}
public static string MakeFilename(this DateTime dt, string format)
{
return string.Format(format, MakeFilename(Now));
}
}
...
Console.WriteLine(Now.MakeFilename(#"c:\logs\log{0}.log");
There can't be no ':' in a file name, that's why.

Removing data from returned information.

I am making an SQL Query that brings back a list of files and their paths. They have different file paths and different file names ofc.
The file names are dates and time in the following format:
YearMonthDayHourMinuteSeconds
What I need to do is take the filepath that has the latest date and time, strip off everything except the date and time part and then using the date and time re-query the database.
I have very few ideas on how to do this.
EDIT: The date will be changing and I need to take the latest when ever the program is run.
My first idea would be to treat everything the query returns as strings
When you get your result set, you could iterate through it storing the record you want in a string or multiple strings. You can compare strings with firststring.Compare(secondstring) it returns 1 or greater if the secondstring is alfabeticaly after firststring.
Then use substring to extract the part of the string you want
string inf = latestdate.Substring(startindex, length);
Hope this helps
use the standard .NET file operation libraries
something like:
using System.IO;
...
string myFileNameWithFullPath;
...
DateTime newDate = DateTime.Parse(Path.GetFileName(myFileNameWithFullPath));
string tmps = Path.GetFileNameWithoutExtension(filenameFromSQL);
DateTime myDateTime = DateTime.Parse(String.Format("{1}/{2}/{0}",
tmps.Substring(0,4), tmps.Substring(5,2), tmps.Substring(7,2));

Categories