So I'm writing an app and without any problem I was getting streamwriter to write new lines using the WriteLine. However, when I got to a certain textbox it automatically started indenting. Please see below image and code:
This is under a save button
SaveFileDialog sfd = new SaveFileDialog();
sfd.InitialDirectory = #"C:\DR\Desktop\4-22-18";
sfd.RestoreDirectory = true;
sfd.FileName = "G-12";
sfd.Filter = "txt files(*.txt)|*.txt| Word Files | *.doc";
if (sfd.ShowDialog()==DialogResult.OK)
{
Stream fileStream = sfd.OpenFile();
StreamWriter sw = new StreamWriter(fileStream);
sw.WriteLine(lblDate.Text);
sw.WriteLine(lblTime.Text);
sw.WriteLine("\r");
sw.WriteLine("G-12"+"\t"+ lblNotes.Text + " " + txtNotes.Text);
sw.WriteLine("==========================================");
sw.WriteLine(lblSG.Text+" "+ nmSG.Text);
sw.WriteLine("==========================================");
sw.WriteLine(lblTinWeight.Text + " " + nmTinWeight.Text);
sw.WriteLine(lblKIO3.Text + " "+ nmKIO3Volume.Text);
sw.WriteLine(lblKIO3N.Text + nmKIO3N.Text);
sw.WriteLine(lblTinPercentage.Text + " "+ lblTinPercent.Text);
sw.WriteLine(lblTinGram.Text + lblTinGrams.Text);
sw.WriteLine("==========================================");
sw.WriteLine(lblNeutWeight.Text+nmNeutWeight.Text);
sw.WriteLine(lblNeutVolume.Text+nmNaOHVolume.Text);
sw.WriteLine(lblNeutNormality.Text + nmNaOHNormality.Text);
sw.Close();
}
enter image description here
The text box contains a space. Verify this by looking the value of lblTinWeight.Text (or a different textbox, not sure) in the debugger.
Related
I'am trying to add new text to exist file which i created but when he click save i have always the same save us. Program adding text but i always must create new text.
string text = System.IO.File.ReadAllText(#"D:\test.txt");
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
text = "iNFO ADD" + " = " + textBox3.Text + Environment.NewLine;
File.AppendAllText(saveFileDialog1.FileName, text);
}
}
You can add your text in string[] or List and after that add in text file.
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
if(saveFileDialog.ShowDialog() == DialogResult.OK)
{
List<string> appendLines = new List<string>()
{
"one string",
"two string"
};
File.AppendAllLines(saveFileDialog.FileName, appendLines);
}
}
Change text = to text +=, and also use WriteAllText in case the file is the same as the one you just read in (otherwise you will read in the file, then append the same data back into the file). Currently you are reading a file into the variable text, the immediately overwriting all of that data with new data.
string text = System.IO.File.ReadAllText(#"D:\test.txt");
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
text += "iNFO ADD" + " = " + textBox3.Text + Environment.NewLine;
File.AppendAllText(saveFileDialog1.FileName, text);
}
Or, if you really want to use AppendAllText and simply want to append to an existing file, you actually want to leave your text = unchanged and do this instead (no reason to read in the file):
string fileName = #"D:\test.txt";
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string text = "iNFO ADD" + " = " + textBox3.Text + Environment.NewLine;
File.AppendAllText(fileName, text);
}
Ok, so I'm new to C# and don't know what I'm doing wrong.
At the top of the button click event I have this variable:
InformationDump infodump;
infodump = new InformationDump();
After that I have the rest of the code which is meant to path to the user desktop and save whatever is filled out in the textbox's into a separate window (part of the same program):
infodump.richTextBox1.Text = textBox1.Text + ", " + textBox2.Text + ", " + textBox3.Text + ", " + textBox4.Text + ", " + comboBox1.SelectedItem;
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filename = path + "\\" + DateTime.Now.ToString("HH.mm.ss") + System.Environment.UserName + ".txt";
infodump.richTextBox1.SaveFile(filename, RichTextBoxStreamType.RichText);
Thanks in advance.
This is happening because you are creating an instance of the form (InformationDump) then try to use the RichTextBox instance but the form then will not go through the standard loading and initialization process therefore as I reproduced, the file will be created but will be empty.
It is very interesting, but if you do repeated save it works!
infodump.richTextBox1.SaveFile(filename, RichTextBoxStreamType.RichText);
// zero bytes
infodump.richTextBox1.SaveFile(filename, RichTextBoxStreamType.RichText);
// works!
I'm doing some WPF exercises and I could succesfully write a file with content on it.
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text file (*.txt)|*.txt";
sfd.ShowDialog();
using (StreamWriter sw = File.CreateText(sfd.FileName))
{
sw.Write(container.Text);
sw.Close();
}
MessageBox.Show("File " + sfd.FileName + " created at " + DateTime.Now.ToString());
container.ResetText();
That using (StreamWriter) is rising the exception.
If I try to save a file, but, close the window before informing a file name , things go bad.
How can I avoid that ? I tried checking if the file is null ( both above and inside the using statement but it still goes off.
You need to check the result of ShowDialog:
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text file (*.txt)|*.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(sfd.FileName, container.Text);
MessageBox.Show("File " + sfd.FileName + " created at " + DateTime.Now.ToString());
container.ResetText();
}
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 + ",");
}
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");
}
}