I have this path which saves a excel sheet on the basis of date and time.
It is Showing
System.NotSupportedException
What is the correct Format ?
string strpath = Server.MapPath("~/SavedFolder/"+ username+ "/"+DateTime.Now+".xlsx/");
Your problem (after removing the final slash) is caused by the conversion of DateTime.Now to a string using your locale settings. This produces a string like this
h:\temp\08/06/2016 09:19:42.txt
and this string contains invalid chars as you can see calling Path.GetInvalidFileNameChars (the slash, backslash are confused as part of a folder name, while the colon is simply not a valid char for a file)
You can use the formatting capabilities of NET to prepare your file name in this way
filename= DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
string strpath = Server.MapPath("~/SavedFolder/"+ username+ "/"+ filename + ".xlsx");
Usually, when I need to tag my files with a datetime part, I put the date parts in the order of year, month, day, hour, minute, second to get an easy way to see them sorted in any file explorer that supports ordering by name.
Check the output of DateTime.Now.ToString() (which been called in this case), it seems that it contains characters which is not allowed path of file name.
string strpath = Server.MapPath("~/SavedFolder/"+ username+ "/"+DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") +".xlsx");
Related
Using .NET and C# I am attempting to create a directory at the specified path of "" + DateTime.Now
Function Call:
Directory.CreateDirectory("" + DateTime.Now);
However, I get this error message:
System.NotSupportedException: "The given path's format is not
supported".
Why is this?
There are various characters which are not allowed in path names. These include : and /.
DateTime.Now.ToString() returns a string such as 01/20/2020 16:49:35, which contains both / and : characters.
Therefore the string returned by DateTime.Now.ToString() is not suitable for use as a file or directory name.
You will need to give DateTime.Now.ToString a format string, which tells it how to render the current time in a way which does not use / or : characters. You can find the list of formats on this page, but you probably want something like:
string now = DateTime.Now.ToString("yyyyMMdd_HHmmss");
Which gives for example 20200120_164935.
DateTime.Now gets a DateTime object which is set to the current date and time on the local computer.
When this is converted to a string it contains ":" and "/"s. Colons and slashes are not valid in file or path names. They are considered illegal and "dangerous".
I am exporting a data from SQL Query into CSV and then renaming the csv file into a name-with-date however i have a problem with renaming the csv file to not have any special characters.
I have tried replacing the "." or "/" with an empty space but that does not bear fruitful for me. My code as per below :
string filepath1 = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\import-contacts-" +
DateTime.Now.Date.ToString("yyyy.MM.dd").Replace('/', ' ') + ".csv";
My output should be import-contacts-20190606.csv
However i am getting import-contacts-2019.06.06.csv at the moment.
How can i fix my output?
You can use string interpolation for this, to make it much clearer to read. Also, just don't put anything in the string you don't want...
var filePath = AppDomain.CurrentDomain.BaseDirectory +
$"\\Logs\\import-contacts-{DateTime.Today.AddDays(-1):yyyyMMdd}.csv";
or (if you prefer a 1-liner)...
var filePath = $"{AppDomain.CurrentDomain.BaseDirectory}\\Logs\\import-contacts-{DateTime.Today.AddDays(-1):yyyyMMdd}.csv";
Here's a working example...
https://dotnetfiddle.net/aYAgVr
Note DateTime.Now would work exactly the same, since you're formatting the output to only show the date parts. I'm just pedantic about not using a DateTime for a date!
Just remove . from ToString() method. Try like:
string = AppDomain.CurrentDomain.BaseDirectory + "\Logs\import-contacts-" + DateTime.Now.ToString("yyyyMMdd").Replace('/', ' ') + ".csv";
EDIT (per new req):
DateTime.Now.AddDays(-1).ToString("yyyyMMdd")
The problem is that you're relying on the current culture to provide the right format, but current means different things to different users, and apparently does not produce the format you want.
The solution is simple, use a specific culture to get a specific format:
DateTime.Today.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture)
should always use dots as separators.
It will work for you.
string path = string.Format(#"{0}Logs\import-contacts-{1}.csv", new object[] { AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyyMMdd") });
I am trying to find the file that has the highest date in a single directory. The problem is that the dates are attached to filenames. I am using the following code to try to pull the max date but am running into trouble with the ParseExact.
//Gather all of the files in the local directory
var files = Directory.EnumerateFiles(r.getLeadLocalFile());
returnDateTime = files.Max(f => DateTime.ParseExact(f, "MMddyyXXXX.csv", CultureInfo.InvariantCulture));
I continue to get the following error:
String was not recognized as a valid DateTime.
I can tell that the value of the file path is being passed in because the value of 'f' is below:
\\\\vamarnas02\\users\\meggleston\\User Files\\Leads\\110716ENH9.csv
The value of ENH9 can change depending on the file.
How can I get the DateTime from my filename?
Here's another approach. No need to split out anything. But one bad filename (as with your current approach) will ruin it:
//Gather all of the files in the local directory
var files = new DirectoryInfo(r.getLeadLocalFile()).GetFiles("*.csv");
returnDateTime = files.Max(f => DateTime.ParseExact(f.Name.Substring(0, 6), "MMddyy", CultureInfo.InvariantCulture));
You need to split out the date text before parsing. The following code snippet should help.
Assume the variable f is the filename.
DateTime.ParseExact(f.Substring( f.LastIndexOf("\\") + 1, 6), "MMddyy", CultureInfo.InvariantCulture);
Do you really need to use ParseExact here? Because it seems that you just need to get Int32 values and compare them afterwards.
So another approach: you can extract your date parts with some regex, from the path provided. For example you can use this one:
\\\d{6} // 2 slashes and 6 digits. I'm not an expert in regex, but seems that this one is enough for your task.
And trim the \\ part afterwards. So something like this in the loop:
private string ExtractDateFromFilename(string filename) {
var m = Regex.Match(filename, #"\\\d{6}");
if (!string.IsNullOrEmpty(m.Value))
return m.Value.Substring(1);
return "";
}
Try only passing the filename "110716ENH9.csv" instead of the full path of the file.
From MSDN DateTime.ParseExact Documentation:
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
From what you've provided, your format does not match exactly.
--
Only pass the first 6 characters of the filename to the ParseExact function and amend your format to be "MMddyy."
In my Application there is a class that works with PdfSharp to generate some PDF reports. I specified output folder as a string with verbatim
string file_path = #"D:\Intranet\Students\DailyMarks\";
Also there is a StringBuilder that generates file name based on some ID and DateTime:
... sb.Append(document.Type); sb.Append(document.Id); sb.Append(DateTime.Now.ToShortString());
And finally I do the following
file_path + sb.toString();
But my Application cathes an exception. After debugging session I see that actually my file_path is
file_path = "D:\\Intranet\\Students\\DailyMarks\\...";
As I understand it happens after concatenation of origin file with StringBuilder's toString() call.
I tried to replace file_path string with something like this:
file_path = file_path.Replace(#"\\",#"\");
but it doesn't work. Where did I do wrong?
Probably this is caused by the DateTime.Now.ToShortString() method, which adds forbidden characters to the path (:).
It's totally fine.
"D:\\Intranet\\Students\\DailyMarks\\..." == #"D:\Intranet\Students\DailyMarks\..."
In regular string you need to escape slashes, in verbatim it's done automatically
Another similar situation I faced today was about sending Japanese 「:」 (colon with whole inside) as a file's name's element and it worked. I wonder, why Russian colon calls an exception and Japanese not. Very interesting.
I need to hardcode a file path, but the path contains spaces, so it is not being interpreted properly. I haven't found a workaround that worked :( This is the filepath I need to use but the path is broken at the first space so it reads NetBrain\Personnel\Mangers\Daily which is invalid so it throws an error
oWB = (Excel._Workbook)oXL.Workbooks.Open("\\\\NetBrain\\Personnel\\Managers\\Daily And Weekly Logs\\Mitchell.xls");
Your options are to avoid spaces (because even in this millennium they cause problems in unexpected places), or to quote the names so that they are treated as a single path instead of two or more fragments.
To quote a file path you just need to add double quotes ", like this:
path = "\"" + path + "\"";
Take care not to quote a path that is already quoted.
Most places where you pass a path will not needed the quoted path - it's usually only if a path is passed through a command line interface that it will require quoting.
This may or may not work with the specific Excel example that you posted, as it how it works all depends on how Excel handles the path internally.
Define it in a constant or static variable
const String myPath = #"\\NetBrain\Personnel\Managers\Daily And Weekly Logs\Mitchell.xls"
oWB = (Excel._Workbook)oXL.Workbooks.Open(myPath)
Adding second option with your comment update
Try
const String myPath = #"\\NetBrain\Personnel\Managers\Daily And Weekly Logs\Mitchell.xls"
Uri u = new Uri(myPath);
oWB = (Excel._Workbook)oXL.Workbooks.Open(u.AbsoluteUri);