I have an application that reads a delimited file using ODBC. The connection string is as follows:
cs = #"Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=" + sPath1;
One of the companies providing a file is not using a header row, and I'm losing the first row of data. Putting HDR=No in the connection string does not seem to help. There is a schema.ini in the target directory.
cs = #"Driver={Microsoft Text Driver (*.txt; *.csv)};HDR=No;DBQ=" + sPath1;
What's the best way to read the first row? I haven't tried the Excel driver because I'm afraid it will interpret data differently.
The solution is to be sure there is a line reading
ColNameHeader=False
in the schema.ini. Documentation can be found here:
http://msdn.microsoft.com/en-us/library/ms709353%28VS.85%29.aspx
To follow up on the correct answer, you can also write a function to create/write your schema file as a FileStream at run time. Include ColNameHeader=False (or pass it as a parameter) when you write to the file. The file name must be schema.ini
private void writeSchema(string decimalPointOverride = "", string header="True")
{
try
{
FileStream fsOutput = new FileStream( myDirectory + "\\schema.ini", FileMode.Create, FileAccess.Write);
StreamWriter srOutput = new StreamWriter(fsOutput);
string s1, s2, s3, s4, s5, s6;
s1 = "[" + "OutputFileName.CSV" + "]";
s2 = "ColNameHeader=" + header;
s3 = "Format=" + this.strFormat;
s4 = "MaxScanRows=25";
s5 = "CharacterSet=" + this.strEncoding;
//set decimal point if exists, otherwise put empty string ""
s6 = (decimalPointOverride == "") ? "" : "DecimalSymbol=" + decimalPointOverride + "\r\n";
srOutput.WriteLine(s1.ToString() + "\r\n" + s2.ToString() + "\r\n" + s3.ToString() + "\r\n" + s4.ToString() + "\r\n" + s5.ToString() + "\r\n" + s6.ToString());
srOutput.Close();
fsOutput.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message, "writeSchema");
}
}
Related
I want to add the link to my local file into one of the columns of Exported CSV file.So that when user clicks on the link the local file open. I have searched the internet for this but can't find any good solution.
Here is the screenshot of what i try to do -
Suppose when user clicks on File path selected row file full name then upon click i should open the file at that localtion.
My code to generate the CSV file is-
public void GetExportDetailsCSV(ExportInformation ExportInfo)
{
StringBuilder cameraRows = new StringBuilder();
string filePath = ExportInfo.ExportOutputPathAtClient + SLASH_STRING + "ExportDetails.csv";
string columnsNames = "File Name ,File Path" + "\r\n";
if(Directory.Exists(ExportInfo.ExportOutputPathAtClient))
{
try
{
foreach (string newPath in Directory.GetFiles(string.Format("{0}{1}", ExportInfo.ExportOutputPathAtClient, SLASH_STRING), "*" + ExportInfo.VideoFileFormat.ToString(), SearchOption.AllDirectories))
{
FileInfo FileDetails = new FileInfo(newPath);
cameraRows.Append(string.Format("{0},{1}\r\n", FileDetails.Name, FileDetails.FullName));
}
string FinalData = "\nExport Remarks : Simple Export " + "\n\n" + "," + "," + "," + "," + "File Details" + "," + "\r\n" + "\r\n" + columnsNames + "\n " + cameraRows;
using (var stream = System.IO.File.CreateText(filePath))
{
stream.WriteLine(FinalData);
}
}
catch(Exception ex)
{
}
}
}
My question is simple how can i put file location value as a link in my Exported CSV file.
Thankyou!
Try using the Hyperlink function. Check this link
You can try this sample. Open notepad type below the line and save it as CSV.
This,is,demo,"=HYPERLINK(""http://www.google.com/"",""Link"")"
Hopefully, this will solve the problem.
I have a problem that is:
I have a program that writes on a file throw File.WriteAllText, and it works fine until I close the activity in which it writes. When I close that activity, the file hasn't saved the changes I've made.
What might be the problem?
var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filename = Path.Combine(path, "Produtos.txt");
atual = File.ReadAllText (filename);
novo = atual + System.Environment.NewLine + _nome + ";" + _preco + ";" + _unidade + ";" + _categoria;
File.WriteAllText (filename, novo);
I have been doing this for a university project and have run into a problem. I have managed to load multiple lines from a file but I am unable to save them back to a file. I can save a single string to the file, which is the last string processed but that is it. I may be doing it completely wrong by performing a loop, but I cant think of any other way to do it. The coding for the savefile section is as follows:
case "s":
case "8":
{
int savecount = 0;
string savestring = "";
//Clear the text file ready to be saved
using (FileStream fs = File.Create("billing.txt"))
{
}
while (savecount != CustomerCount)
{
using (StreamWriter save = new StreamWriter("billing.txt"))
{
//Create the string to save to the file
savestring = CustomerNumber[savecount] + ","
+ CustomerName[savecount] + ","
+ Address[savecount] + ","
+ RateScheme[savecount] + ","
+ PeakKWH[savecount] + ","
+ OffPeakKWH[savecount] + ","
+ StandardKWH[savecount];
Console.WriteLine(savestring);
save.WriteLine(savestring);
savecount++;
Console.ReadLine();
}
}
Console.WriteLine("All data saved successfully");
Console.ReadLine();
break;
}
Not sure where to go from here. Any help would be appreciated
You should open the file for saving before the loop. E.g.
using (StreamWriter save = new StreamWriter("billing.txt")) {
while (savecount != CustomerCount) {
// rest of your code here
At the moment, you are opening the file in each loop, writing a line out. Then re-opening it (and losing the data already written).
As pointed out in the comments, you don't need to call File.Create. By default the StreamWriter will overwrite the existing file.
You need the while loop inside the using { } As it is you're overwriting your data each time, leaving the last item in your file when you look at it:
using (StreamWriter save = new StreamWriter("billing.txt"))
{
while (savecount != CustomerCount)
{
//Create the string to save to the file
string savestring = CustomerNumber[savecount] + ","
+ CustomerName[savecount] + ","
+ Address[savecount] + ","
+ RateScheme[savecount] + ","
+ PeakKWH[savecount] + ","
+ OffPeakKWH[savecount] + ","
+ StandardKWH[savecount];
Console.WriteLine(savestring);
save.WriteLine(savestring);
savecount++;
Console.ReadLine();
}
}
What You are doing wrong is, you are opening the file in each iteration of while, writing a line in file and Then again re-opening the file and overwriting the contents. You can rechange your code
using (StreamWriter save = new StreamWriter("billing.txt"))
{
while (savecount != CustomerCount)
{
// rest of string formation of saveString logic and save.WriteLine(savestring); goes here
.....
}
}
I think you can use a simple code also where you can save all your input string in an List and use File.WriteAllLines function as
{
....
List<string> Customers = new List<string>();
for (savecount = 0; savecount < CustomerCount; savecount++)
{
//Create the string to save to the file
Customers.Add( CustomerNumber[savecount] + "," + CustomerName[savecount] + "," + Address[savecount] + "," + RateScheme[savecount] + "," + PeakKWH[savecount] + "," + OffPeakKWH[savecount] + "," + StandardKWH[savecount]);
Console.WriteLine(Customers[savecount]);
}
string filePath = "billing.txt"; // This is your file path where all the contents are to be written
File.WriteAllLines(filePath, Customers);
..........
}
You need:
using (StreamWriter save = new StreamWriter("billing.txt")) {
while (savecount != CustomerCount) {
You have to open file before loop because opening inside deletes all previous data written in that, also it takes some time for opening.
However you can open file inside loop, but you need to set append file, it would be:
StreamWriter save = new StreamWriter("billing.txt", true)
This option is slower and you may need to clear file before opening in append mode, so it isn't the best option.
I use a file upload control to save a CSV file into server. CSV File having a column deviceid.It has the 17 digit number like '12345678901234567' but treated as a string. Now i am using the below code to save this csv in server.
Now i open the same file from server but the same column format changed from string to number with exponential format and the last two digit treated as 0. How can i store the csv without changing datatype.
string rnd_number = Convert.ToString(random.Next(1, 100000));
path = System.IO.Path.GetFileName(fp_excel.PostedFile.FileName);
SaveLocation = Server.MapPath("Document" + "\\" + folder.Trim() + "\\" + rnd_number + fileExt);
path = "../Document/" + folder + "/" + rnd_number + fileExt;
ViewState["path"] = Server.MapPath(#"Document/" + folder + "/" + rnd_number + fileExt);
fp_excel.PostedFile.SaveAs(SaveLocation);
lbl_msg.Text = path;
update(Server.MapPath(#"Document/" + folder + "/" + rnd_number + fileExt));
Can you try format number to string like below
Dim style As String = "<style>.textmode{mso-number-format:\#;}</style>"
Refer : http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
I can't seem to figure out how to write data to a file without overwriting it. I know I can use File.appendtext but I am not sure how to plug that into my syntax. Here is my code:
TextWriter tsw = new StreamWriter(#"C:\Hello.txt");
//Writing text to the file.
tsw.WriteLine("Hello");
//Close the file.
tsw.Close();
I want it to write Hello every time I run the program, not overwrite the previous text file. Thanks for reading this.
Pass true as the append parameter of the constructor:
TextWriter tsw = new StreamWriter(#"C:\Hello.txt", true);
Change your constructor to pass true as the second argument.
TextWriter tsw = new StreamWriter(#"C:\Hello.txt", true);
You have to open as new StreamWriter(filename, true) so that it appends to the file instead of overwriting.
Here's a chunk of code that will write values to a log file. If the file doesn't exist, it creates it, otherwise it just appends to the existing file. You need to add "using System.IO;" at the top of your code, if it's not already there.
string strLogText = "Some details you want to log.";
// Create a writer and open the file:
StreamWriter log;
if (!File.Exists("logfile.txt"))
{
log = new StreamWriter("logfile.txt");
}
else
{
log = File.AppendText("logfile.txt");
}
// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(strLogText);
log.WriteLine();
// Close the stream:
log.Close();
Best thing is
File.AppendAllText("c:\\file.txt","Your Text");
Look into the File class.
You can create a streamwriter with
StreamWriter sw = File.Create(....)
You can open an existing file with
File.Open(...)
You can append text easily with
File.AppendAllText(...);
First of all check if the filename already exists, If yes then create a file and close it at the same time then append your text using AppendAllText. For more info check the code below.
string FILE_NAME = "Log" + System.DateTime.Now.Ticks.ToString() + "." + "txt";
string str_Path = HostingEnvironment.ApplicationPhysicalPath + ("Log") + "\\" +FILE_NAME;
if (!File.Exists(str_Path))
{
File.Create(str_Path).Close();
File.AppendAllText(str_Path, jsonStream + Environment.NewLine);
}
else if (File.Exists(str_Path))
{
File.AppendAllText(str_Path, jsonStream + Environment.NewLine);
}
using (StreamWriter writer = File.AppendText(LoggingPath))
{
writer.WriteLine("Text");
}
none of the above did not work I found the solution myself
using (StreamWriter wri = File.AppendText("clients.txt"))
{
wri.WriteLine(eponimia_txt.Text + "," + epaggelma_txt.Text + "," + doy_txt.Text + "," + dieuthini_txt.Text + ","
+ proorismos_txt.Text + "," + poly_txt.Text + "," + sxePara_txt.Text + "," + afm_txt.Text + ","
+ toposFortosis_txt.Text + ",");
}