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") });
Related
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");
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);
I've read many solutions to this problem and have tried all of them but cannot find the correct way to accomplish this task. My code is:
p.StartInfo.Arguments = path;
I need the path variable to be surrounded by " marks since it is a path to a file that has spaces in the directory names and file name. How can I put a " around the start and end of the path variable? Psudo code would be:
p.StartInfo.Arguments = DoubleQuote + path + DoubleQuote;
As a followup to this situation - once my .exe file received the path - the path was in its entirety following the "\"" suggestions. However, I had to enclose the path in the .exe file code in "\"" so it also could find the .xlsx file since the path and file name had spaces in them. Just wanted to followup with this for anyone else with this situation and wondering why the command line argument was ok, but the .exe file was not finding the file - both apps need enclosed in "\"".
Not sure what solutions you've seen and tried but you need to escape the quotes
p.StartInfo.Arguments = "\"" + path + "\"";
or if you want to use the verbatim string literal (use "" to escape)
p.StartInfo.Arguments = #""" + path + """;
If you have a lot of parameters, you might find the String.Format method easier to maintain.
p.StartInfo.Arguments = string.Format(#"""{0}""", path);
You just need to append the double quote character to the start and end of the string. Creating the double quote can be done in either of the following ways
"\""
#""""
I have a button that when the user clicks it, it must go to a specified URL.
But I have to create my URL out of the values coming from database and most importantly, I need to modify the values coming from database before I make a URL out of it.
Suppose the values from database is
country- France
hotel - Hotel Movenpick
Now first I have to turn the capitals from above values to lowercase, then spaces to '-' sign.
Then i will have to create my URL with these modified values as below.
http://www.travel.com/france/hotel-movenpick
I have never done this before. Please provide me some reference for doing this task. I am coding in c#.
How about:
string fixedCountry = country.ToLower(CultureInfo.InvariantCulture)
.Replace(" ", "-");
string fixedHotel = hotel.ToLower(CultureInfo.InvariantCulture)
.Replace(" ", "-");
string url = "http://www.travel.com/" + fixedCountry + "/" + fixedHotel;
Note that this won't fix up any accented characters or other symbols. It becomes more complicated if you want to do that. It will depend on how much you trust your data to not contain that sort of thing.
If you need to make this any more complicated, or need to do it anywhere else, I suggest you create a "string fixing" method which munges it appropriately, then call it for each of your fields.
EDIT: Removing accented characters is interesting. .NET makes this fairly easy, but I don't know what it will do for your "ae" situation - you may need to special-case that. Try this though, as a starting point:
static string RemoveAccents (string input)
{
string normalized = input.Normalize(NormalizationForm.FormKD);
Encoding removal = Encoding.GetEncoding
(Encoding.ASCII.CodePage,
new EncoderReplacementFallback(""),
new DecoderReplacementFallback(""));
byte[] bytes = removal.GetBytes(normalized);
return Encoding.ASCII.GetString(bytes);
}
In C#, I have a filename that needs to converted to be double-escaped (because I feed this string into a regex).
In other words, if I have:
FileInfo file = new FileInfo(#"c:\windows\foo.txt");
string fileName = file.FullName;
fileName is: c:\\\\windows\\\\foo.txt
But I need to convert this to have sequences of two literal backslashes \\ in the fileName.
fileName needs to be #"c:\\\\windows\\\\foo.txt", or "c:\\\\\\\\windows\\\\\\\\foo.txt".
Is there an easy way to make this conversion?
I Think you're looking for Regex.Escape
Regex.Escape(#"c:\test.txt") == #"C:\\Test\.txt"
notice how it also escapes '.'
simplest without resorting to regex for this part:
string fileName = file.FullName.Replace(#"\", #"\\\\");
based on OP, but I think you really want this:
string fileName = file.FullName.Replace(#"\", #"\\");
That being said, I can't see how you want to use it... it shouldn't need escaping at all... maybe you should post more code?