how to add time to C# console array - c#

I would like to know how to get the filename into an array and load the filename to CSV file. For example, this is the filename, File_1_20170428101607. I want the file name (date and time format – 28/04/2017 10:16:07) to be parse into a column in the output file (csv file). This is the code for time, can you please check and how to add the time to array to be parse to csv file?
private static string[] GetFileNames(string path, string filter)
{
string fileName = #”C:\\Desktop\\File_1_20170428101607.csv”;
string result;
result = Path.GetFileName(fileName);
Console.WriteLine(“GetFileName(‘{0}’) returns ‘{1}'”,
fileName, result);
string[] files = Directory.GetFiles(path, filter);
for (int i = 0; i parsing was not possible -> return null
{
return null;
}
}
private static DateTime? ParseDateFromFilename(string filename)
{
//regex is used to extract the 14 digit timestamp from filename
var timestamp = Regex.Match(filename, #"\d{14}$");
if (!timestamp.Success)
{
//if no match was found return null
return null;
}
try
{
//try to parse the date with known timestamp and return
return DateTime.ParseExact(timestamp.Value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
}
catch
{
//any error -> parsing was not possible -> return null
return null;
}

You can try this:
First create a StringBuilder that will contain csv content:
StringBuilder csv = new StringBuilder();
string filePath = "...";
Next create a for loop and take values for two columns and append it do StringBuilder
//for loop start
string fileName = "File_1_20170428101607";
string datePart = fileName.Split('_').Last();
DateTime dt = DateTime.ParseExact(datePart, "yyyyMMddhhmmss", null);
string dateString = dt.ToString("dd/mm/yyyy hh:MM:ss", System.Globalization.CultureInfo.InvariantCulture);
var firstColVal = fileName;
var secondColVal = dateString;
var newLine = string.Format("{0},{1}", firstColVal, secondColVal);
csv.AppendLine(newLine);
//loop end
After the for loop save StringBuilder content to your csv file:
File.WriteAllText(filePath, csv.ToString());

Related

Formatting and overriding the default cell format of date & time while writing it in an Excel Sheet

We are capturing the entire table data inside the $("#dvtablerptTDetails")[0].innerHTML containing all the data and the same will be saved in the session and later converted to string & sent to Response.Write() that would later create an Excel file containing data of filetype xlsx
Here the requirement is to override the default cell format when writing the data, especially for the date & time format of an individual cell.
By default, when saved and viewed, Cell Format will be in dd/mm/yyyy hh:mm
But Expected Cell Format should be in dd-MMM-yyyy HH:mm:ss
So tried to modify data prefixing and suffixing with Dot(.) or At the rate(#). But it worked printing as per our requirement. But unable to escape special characters. Since it writes exactly as it is.
Below here is the partial snippets
DateTimeUtility objDTU = new DateTimeUtility();
RegisteredDate = objDTU.GetActualDateTime((DateTime)(dsTestcener.Rows[i]["TestApprovedDate"])).ToString("dd-MMM-yyyy HH:mm:ss");
public DateTime GetActualDateTime(DateTime utcDateTime)
{
DateTime actualDateTime;
if (HttpContext.Current.Session["UserTimeZone"] != null)
{
actualDateTime = utcDateTime.AddHours(Double.Parse(HttpContext.Current.Session["UserTimeZone"].ToString(), CultureInfo.InvariantCulture));
}
else
{
actualDateTime = utcDateTime;
}
return actualDateTime;
}
Tried to modify the above data assigned to RegisteredDate object
objDTU.GetActualDateTime((DateTime)(dsTestcener.Rows[i]["TestApprovedDate"]))
.ToString("dd-MMM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Actual Data(html) : 28-Feb-2020 15:14:38
Actual Data(xsl) : 28/02/2020 15:14
Expected Data(xsl): 28-Feb-2020 15:14:38
objDTU.GetActualDateTime((DateTime)(dsTestcener.Rows[i]["TestApprovedDate"]))
.ToString("dd-MMM-yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);
Actual Data(html) : 28-Feb-2020 15:14:38.313
Actual Data(xsl) : 14:38.
Expected Data(xsl): 28-Feb-2020 15:14:38.313
objDTU.GetActualDateTime((DateTime)(dsTestcener.Rows[i]["TestApprovedDate"]))
.ToString("dd-MMM-yyyy HH:mm:ss");
Actual Data(html) : 28-Feb-2020 15:14:38
Actual Data(xsl) : 28/02/2020 15:14:38
Expected Data(xsl): 28-Feb-2020 15:14:38
The below coding snippets shows how does the html data get captured & traversed to Response.Write()
function ExportAnalysis() {
try {
var batchDetails = $("#displayDetails").html();
var message = JSON.stringify({ BatchDetails: batchDetails });
CallAjaxJSON(message, '<%=Request.ApplicationPath%>' + "/MES/TestCentre.aspx/PersistBatchDetails", OnExportBatchSuccess, OnFailure);
var url = '<%=Context.Request.ApplicationPath%>' + '/MES/ExportToExcel.aspx?name=Analysis Response';
window.open(url);
} catch (e) {
}
return false;
}
[System.Web.Services.WebMethod()]
public static string PersistBatchDetails(object BatchDetails)
{
try
{
HttpContext.Current.Session["DashboardBatchInfo"] = BatchDetails;
}
catch (Exception ex){}
return "S001";
}
protected void Page_Load(object sender, EventArgs e)
{
string fileName = "Excel";
if (!String.IsNullOrEmpty(Request.QueryString["name"]))
fileName = Request.QueryString["name"];
Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
string BatchDetails = Convert.ToString(Session["DashboardBatchInfo"]);
Response.Write(BatchDetails);
Response.End();
Session["DashboardBatchInfo"] = null;
}
How should we need to achieve in writing the expected data in the respective format?
Finally found the solution:
[System.Web.Services.WebMethod()]
public static string PersistBatchDetails(object BatchDetails)
{
try
{
string pattern = #"\d{4}\-\d{2}\-\d{2}\s\d{2}\:\d{2}\:\d{2}|\d{2}\-[a-zA-Z]{3}\-\d{4}\s\d{2}\:\d{2}\:\d{2}";
Regex r = new Regex(pattern);
var res = r.Replace(BatchDetails.ToString(), new MatchEvaluator(ConvertDateFormat));
HttpContext.Current.Session["DashboardBatchInfo"] = res;
}
catch (Exception ex)
{
BasePage objBasePage = new BasePage();
objBasePage.Log.LogError("Page: TestActivation, Method: GetBatchesList " + ex.Message, ex);
objBasePage = null;
return "S002";
}
return "S001";
}
public static string ConvertDateFormat(Match m)
{
var mydate = DateTime.Parse(m.Value);
return string.Format("=\"{0}\"", mydate.ToString("yyyy-MM-dd hh:mm:ss"));
}

How to avoid duplicate files (of different extensions) when auto generating new files

I have created a program which cleans access and error logs and then outputs them in a new file in the same directory. The input is in format .txt and the output is in format .csv - however it is giving me two output files, one in .csv format and one in .txt format(.txt file is empty) instead of just the .csv file? I can't understand why this is happening.
Below is the two ouput files as shown in the directory:
Below is the code which generates the new file with the unique name:
static FileStream CreateFileWithUniqueName(string folder, string fileName, int maxAttempts = 1024)
{
var fileBase = Path.GetFileNameWithoutExtension(fileName);
var ext = Path.GetExtension(fileName);
// build hash set of filenames for performance
var files = new HashSet<string> (Directory.GetFiles(folder));
for (var index = 0; index < maxAttempts; index++)
{
// first try with the original filename, else try incrementally adding an index
var name = (index == 0)
? fileName
: String.Format("{0} ({1}){2}", fileBase, index, ext);
// check if exists
var fullPath = Path.Combine(folder, name);
if(files.Contains(fullPath))
continue;
// try to create the file
try
{
return new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write);
}
catch (DirectoryNotFoundException) { throw; }
catch (DriveNotFoundException) { throw; }
catch (IOException)
{
}
}
throw new Exception("Could not create unique filename in " + maxAttempts + " attempts");
}
And finally the code below is the code which reads in the existing file and cleans it:
public static void readFile(string fileName)
{
using (var stream = CreateFileWithUniqueName(#"C:\Users\michael\Desktop\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\", fileName))
{
Console.WriteLine("Created \"" + stream.Name + "\"");
newFileName = stream.Name;
Globals.CleanedErrorFileName = newFileName;
}
string CSVfileName = Path.ChangeExtension(newFileName, ".csv");
StreamReader reader = new StreamReader(fileName);
StreamWriter writer = new StreamWriter(CSVfileName);
string line;
string personalIdentifier = new string(fileName.Take(4).ToArray());
string gender = fileName.Substring(fileName.Length - 5, 1);
string classification = fileName.Substring(fileName.Length - 8, 2);
string text = string.Empty;
while ((line = reader.ReadLine()) != null)
{
string[] cleanArray;
cleanArray = new string[5];
var result = line.Split('[')
.Select((element, index) => index % 2 == 0
? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
: new string[] { element })
.SelectMany(element => element).ToList();
cleanArray[0] = personalIdentifier;
cleanArray[1] = gender;
cleanArray[2] = classification;
cleanArray[3] = result[0];
cleanArray[4] = result[2];
cleanArray[4] = cleanArray[4].Substring(7);
cleanArray[4] = cleanArray[4].Replace("]", " ");
cleanArray[4] = cleanArray[4].Insert(15, ",");
cleanArray[3] = cleanArray[3].Remove(cleanArray[3].Length - 2);
cleanArray[4] = cleanArray[4].Substring(0, cleanArray[4].IndexOf(":") + 1);
//re-formatting the date so that it can be accepted by machine learning
var dateString = cleanArray[3];
var date = DateTime.ParseExact(dateString, "ddd MMM dd HH:mm:ss yyyy", CultureInfo.InvariantCulture);
var newDateString = date.ToString("yyyy-MM-dd HH:mm:ss");
//inserting the new date and time into the array
cleanArray[3] = newDateString;
//push each clean array onto the file that has been automatically created at the top
writer.WriteLine(string.Join(", ", cleanArray.Select(v => v.ToString())));
writer.WriteLine();
}
I'm hoping the issue is something small but i can't seem to find it!
Thanks in advance!!
This line is the culprit:
return new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write);
At this point, the file name in fullPath still has .txt extension, this creates the empty .txt file. Then you change extension to .csv and do this:
StreamWriter writer = new StreamWriter(CSVfileName);
which creates the new .csv file
Also, both streams are never closed in your code.

Read each line in file and put each line into a string

I have a text file that I want to read in and put each line from the file into its own string.
So the file will have 4 lines:
2017-01-20
05:59:30
+353879833382
971575 Michael
So in the code I need to read in the file and split up each line and put them into a string i.e the first line will equal to string date, second line will equal to string time etc
Code:
public static void ParseTXTFile(string FileName, int CompanyID)
{
try
{
FileInfo file = new FileInfo(FileName);
string Date;
string Time;
string Phone;
string JobNo;
string Name;
using (CsvReader reader = new CsvReader(new StreamReader(FileName), false))
{
while (reader.ReadNextRecord())
{
}
}
}
catch (Exception ex)
{
throw (ex);
}
}
How do I read in each line of the file and set it to a string?
You may want to consider using the File.ReadAllLines() method which will store each line of your file into an array :
var lines = File.ReadAllLines(FileName);
You could then access each of your properties by their indices as needed :
string Date = lines[0];
string Time = lines[1];
string Phone = lines[2];
string JobNo = lines[3];
string Name = lines[4];

How to Remove number from Extension with string?

I want to remove number from Extension with string in C#.
For Example : "Url1234.pdf" I want the last answer looks like "Url.pdf"
Thank you for your Contribution
var fileName = "";
if (file != null && file.ContentLength > 0)
{
fileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName); //Path.GetFileName(file.FileName);
var extension = System.IO.Path.GetExtension(file.FileName);
DBConnect.OpenDB();
DBConnect.DbSelect("select MAX(ID) as ID from tblFileUpload");
if(DBConnect.dr.Read())
{
fileName += DBConnect.dr["ID"].ToString();
}
DBConnect.CloseDB();
var path = Path.Combine(Server.MapPath("~/File/"), fileName+extension);
new FileUploadLayer().save("aa", fileName, file.ContentLength);
file.SaveAs(path);
UploadFile("aa");
}
I save a file with the extension(.pdf). That file name has numbers also.(Url1234.pdf).So, when i call it back i need to remove those numbers and only need the string part (Url.pdf).
You can use regex as shown or a simple LINQ query, i'd also recommend System.IO.Path:
string originalPath = "Url1234.pdf";
string dir = Path.GetDirectoryName(originalPath); // in this case ""
string extension = Path.GetExtension(originalPath); // .pdf
string fn = Path.GetFileNameWithoutExtension(originalPath); // Url1234
string newFn = String.Concat(fn.Where(c => !Char.IsDigit(c))); // Url
string newPath = Path.Combine(dir, newFn + extension); // Url.pdf
You can use Regex to replace numbers with empty string:
var result1 = Regex.Replace("Url1234.pdf", #"[\d-]", string.Empty);
Add using System.Text.RegularExpressions;

C# Remove Invalid Characters from Filename

I have data coming from an nvarchar field of the SQL server database via EF3.5. This string is used to create a Filename and need to remove invalid characters and tried following options but none of them works. Please suggest why this is such an understandable mystery? Am I doing anything wrong?
I went though almost all of the related questions on this site.. and now posting a consolidated question from all the suggestions/answers from other similar questions.
UPD: The Issue was unrelated..All of these options do work. So posting it to community wiki.
public static string CleanFileName1(string filename)
{
string file = filename;
file = string.Concat(file.Split(System.IO.Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries));
if (file.Length > 250)
{
file = file.Substring(0, 250);
}
return file;
}
public static string CleanFileName2(string filename)
{
var builder = new StringBuilder();
var invalid = System.IO.Path.GetInvalidFileNameChars();
foreach (var cur in filename)
{
if (!invalid.Contains(cur))
{
builder.Append(cur);
}
}
return builder.ToString();
}
public static string CleanFileName3(string filename)
{
string regexSearch = string.Format("{0}{1}",
new string(System.IO.Path.GetInvalidFileNameChars()),
new string(System.IO.Path.GetInvalidPathChars()));
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
string file = r.Replace(filename, "");
return file;
}
public static string CleanFileName4(string filename)
{
return new String(filename.Except(System.IO.Path.GetInvalidFileNameChars()).ToArray());
}
public static string CleanFileName5(string filename)
{
string file = filename;
foreach (char c in System.IO.Path.GetInvalidFileNameChars())
{
file = file.Replace(c, '_');
}
return file;
}
Here is a function I use in a static common class:
public static string RemoveInvalidFilePathCharacters(string filename, string replaceChar)
{
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
return r.Replace(filename, replaceChar);
}
Try this
filename = Regex.Replace(filename, "[\/?:*""><|]+", "", RegexOptions.Compiled)
no invalid chars returned by System.IO.Path.GetInvalidFileNameChars() being removed. – Bhuvan 5 mins ago
The first method you posted works OK for the characters in Path.GetInvalidFileNameChars(), here it is at work:
static void Main(string[] args)
{
string input = "abc<def>ghi\\1234/5678|?9:*0";
string output = CleanFileName1(input);
Console.WriteLine(output); // this prints: abcdefghi1234567890
Console.Read();
}
I suppose though that your problem is with some language-specific special characters. You can try to troubleshoot this problem by printing out the ASCII codes of the characters in your string:
string stringFromDatabase = "/5678|?9:*0"; // here you get it from the database
foreach (char c in stringFromDatabase.ToCharArray())
Console.WriteLine((int)c);
and consulting the ASCII table: http://www.asciitable.com/
I again suspect that you'll see characters with codes larger than 128, and you should exclude those from your string.

Categories