C# save to multiple lines in a text file - c#

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.

Related

How to add local file link to Exported CSV file using C#

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.

Write text to file System.IO.IOException

I have the following code to write some current positions down to a file :
while (onvifPTZ != null)
{
string[] lines = {"\t Act Value [" + curPan.ToString() +
"," + curTilt.ToString() +
"," + curZoom.ToString() + "]","\t Ref Value [" + newPTZRef.pan.ToString() +
"," + newPTZRef.tilt.ToString() +
"," + newPTZRef.zoom.ToString() + "]", "\t Dif Value [" + dPan.ToString() +
"," + dTilt.ToString() +
"," + dZoom.ToString() + "]" + Environment.NewLine };
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(mydocpath, "WriteLines1.txt")))
{
foreach (string line in lines)
outputFile.WriteLine(line);
}
}
I have an error telling me that the process could not use the File at( path..) because its already in use. I tried restarting, and deleting the File( it actually worked one time) but nothing seems to work. Can I write it different so it works, and everytime I start it it makes a new file?
And another question is if somebody knows why it only saves one position...the position is renewed every few milliseconds and I want every position in that file, not only one..how am I supposed to do it?
Same thing works perfectly in the console, also giving the new positions every time, but not in the file.
You should either call StreamWriter.Flush() or set StreamWriter.AutoFlush = true
Additionally before or after writing, I usually check whether the file is locked by another process:
bool b = false;
while(!b)
{
b = IsFileReady(fileName)
}
...
/// <summary>
/// Checks if a file is ready
/// </summary>
/// <param name="sFilename"></param>
/// <returns></returns>
public static bool IsFileReady(string sFilename)
{
// If the file can be opened for exclusive access it means that the file
// is no longer locked by another process.
try
{
using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
{
return inputStream.Length > 0;
}
}
catch (Exception)
{
return false;
}
}

How to force a download of a created file to a users computer c#

I am looking to allow a person to to export journal entries into a text file. I can create a file with all the data but rather strictly saving the file somewhere specific I want to allow a user to download and save the file where they want on their computer. How to I force a download of a file after I create it with StreamWriter. I currently have the following code:
string fileName = "Journal.txt";
using (StreamWriter journalExport = new StreamWriter(fileName))
{
foreach (JournalEntryView entry in journalEnteries)
{
//write each journal entery to file/document
journalExport.WriteLine(entry.timestamp + " - " + entry.author + " (" + entry.authorRole + ")");
journalExport.WriteLine(entry.text);
journalExport.WriteLine("");
journalExport.WriteLine("");
}
}
I am also trying to put this into an ActionResult and return the file.
EDIT:
The following code is my new current code and the direction I am looking to go in, but when I use an ActionLink to call this method, i just get redirected to a new page rather than downloading the file.
string fileName = "Journal.txt";
string filepath = ConfigurationManager.AppSettings["DocumentRoot"] + "\\" + id + "\\" + fileName;
using (StreamWriter journalExport = new StreamWriter(filepath))
{
foreach (JournalEntryView entry in journalEnteries)
{
//write each journal entery to file/document
journalExport.WriteLine(entry.timestamp + " - " + entry.author + " (" + entry.authorRole + ")");
journalExport.WriteLine(entry.text);
journalExport.WriteLine("");
journalExport.WriteLine("");
}
}
byte[] fileData = System.IO.File.ReadAllBytes(filepath);
string contentType = MimeMapping.GetMimeMapping(filepath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = fileName,
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(fileData, contentType);
This might be what you are looking for:
public ActionResult GetFile()
{
...processing stuff...
return File("/files/file.pdf", "application/pdf");
//or
return File("/files/file.pdf", "application/force-download", "donwloadname.pdf");
}

C# compare id from text file in filestream

I need to fill a text file with information about workers. Then I need to read from the file and search for an ID that user tries to find. For example my file contains ids 1,2,3 and if I try to find id 3 and it matches, then this worker's all information is written in console. Otherwise it writes a text A worker cannot be found.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string file = "C:\\Temp\\registery.txt";
FileStream fOutStream = File.Open(file, FileMode.Append, FileAccess.Write);
StreamWriter sWriter = new StreamWriter(fOutStream);
int[] id = { 1, 2, 3 };
string[] name = { "John", "Carl", "Thomas" };
float[] salary = { 3500, 4800, 2100 };
for (int i = 0; i < id.Length; i++)
{
sWriter.WriteLine(id[i] + " " + name[i] + " " + salary[i]);
}
sWriter.Flush();
sWriter.Close();
FileStream fInStream = File.OpenRead(file);
StreamReader sReader = new StreamReader(fInStream);
int id2;
Console.WriteLine("Type worker's id");
id2 = int.Parse(Console.ReadLine());
bool a;
a = sReader.ReadToEnd().Contains(id2);
Console.WriteLine(a);
sReader.Close();
}
}
If you want to create a text file to be searchable, it should be delimited by a separator like comma /TAB
so modify your code:
sWriter.WriteLine(id[i] + "," + name[i] + "," + salary[i]);
To search your text file by id/name/..whatever and use AND/OR, you can use the method described here:
How would I convert data in a .txt file into xml? c#
BTW: Re-factor your code to create the file in a separate method, and the search in other one.
I found a solution myself to my problem and it worked good enough. It might not be the best solution. I removed bool things and I replaced the whole thing with this:
string line;
while ((line = sReader.ReadLine()) != null)
{
if (line.Contains("id: " + id2))
{
Console.WriteLine(line);
break;
}
else if ((line = sReader.ReadLine()) == null)
{
Console.WriteLine("Worker not found with id " + id2);
}
}
And I fixed the upper for loop to look like this:
sWriter.WriteLine("id: " + id[i] + " name: " + name[i] + " salary: " + salary[i]);

How to write data to a text file without overwriting the current data

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 + ",");
}

Categories

Resources