Save text to Exisit file c# - c#

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);
}

Related

Combine 2 textbox text with delimiter

SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text File|*.txt";
sfd.Title = "Save Text File";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = sfd.FileName;
string left = string.Format(EmailTxtbx.Text, Environment.NewLine);
string right = string.Format(PasslTxtbx.Text, Environment.NewLine);
string[] leftSplit = left.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
string[] rightSplit = right.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
string output = "";
if (leftSplit.Length == rightSplit.Length)
{
for (int i = 0; i < leftSplit.Length; i++)
{
output += leftSplit[i] + ":" + rightSplit[i] + Environment.NewLine;
}
}
using (StreamWriter bw = new StreamWriter(File.Create(path)))
{
textBox1.Text = output;
bw.Write(output);
bw.Close();
}
}
Hey. I Have an issue. Lets Say I have 2 Textboxes I want The Textboxes
Be Together:
TextBox1:
Test41
Test414
Test41
TextBox2:
Test55
Test56
Test54
TextBox3:
Test41:Test55
Test414:Test56
Test41:Test54
I want to load 2 files one to the first textbox and for the second textbox and combine With delimiter like ":" I Tried This Code And Its Not working. I'm new on c#.
Hope Someone Can Help Me
I’ll start from scratch. I have 2 textbox. In the first textbok it’s the mails. In the second textbox it’s passwords. What I need to do to combine the textboxes with “:”
Try this code snippet:
var txt1 = textBox1.Lines.Where(a => !string.IsNullOrEmpty(a)).ToArray();
var txt2 = textBox2.Lines.Where(b => !string.IsNullOrEmpty(b)).ToArray();
var txt3 = "";
for(int i = 0; i < txt1.Length; i++)
{
if (i < txt2.Length)
txt3 += $"{txt1[i]}:{txt2[2]}{Environment.NewLine}";
else
txt3 += $"{txt1[i]}{Environment.NewLine}";
}
textBox3.Text = txt3;
Good luck.

Why does WriteLine in C# change my format in Text File?

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.

Avoid exception when writing to null file

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();
}

C# SaveFileDialog

I am using the savefiledialog to save a file. Now I need to check if the name already exists.
If it exists the user needs to get a chance to change the name or overwrite the already existing file.
I have tried it with everything and searched a lot but can't find a solution while I technically think it should be easy to do. In the if (File.Exists(Convert.ToString(infor)) == true) the check must take place.
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = ".xlsx Files (*.xlsx)|*.xlsx";
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = Path.GetDirectoryName(sfd.FileName);
string filename = Path.GetFileNameWithoutExtension(sfd.FileName);
for (int i = 0; i < toSave.Count; i++)
{
FileInfo infor = new FileInfo(path + #"\" + filename + "_" + exportlist[i].name + ".xlsx");
if (File.Exists(Convert.ToString(infor)) == true)
{
}
toSave[i].SaveAs(infor);
MessageBox.Show("Succesvol opgeslagen als: " + infor);
}
}
Just use the OverwritePrompt property of SaveFileDialog:
SaveFileDialog sfd = new SaveFileDialog{ Filter = ".xlsx Files (*.xlsx)|*.xlsx",
OverwritePrompt = true };
MSDN link on OverwritePrompt can be found here.
do this instead
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = ".xlsx Files (*.xlsx)|*.xlsx";
sfd.OverwritePrompt = true;
That should do the work for you
I would use an approach like this:
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = ".xlsx Files (*.xlsx)|*.xlsx";
do
{
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = Path.GetDirectoryName(sfd.FileName);
string filename = Path.GetFileNameWithoutExtension(sfd.FileName);
try
{
toSave[i].SaveAs(infor);
break;
}
catch (System.IO.IOException)
{
//inform user file exists or that there was another issue saving to that file name and that they'll need to pick another one.
}
}
} while (true);
MessageBox.Show("Succesvol opgeslagen als: " + infor);
Catching an exception instead of using File.Exists is really the only way to do it, because something external could create the file between File.Exists and actually writing it, thus throwing an exception you'd have to handle anyway.
This code will loop and continue to prompt the user until the file is successfully written.

Auto Size Format of export from listview values to excel sheet C#

private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog file = new SaveFileDialog {
Title = "Save File To",
FileName = cmbCategory.Text + " " + Description.Text + ".csv",
Filter = "CSV (*.csv)|*.csv",
FilterIndex = 0,
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
if (file.ShowDialog() == DialogResult.OK) {
string[] headers = lstResult.Columns
.OfType<ColumnHeader>()
.Select(header => header.Text.Trim()).ToArray();
string[][] items = lstResult.Items
.OfType<ListViewItem>()
.Select(Details => Details.SubItems
.OfType<ListViewItem.ListViewSubItem>()
.Select(Detail => Detail.Text).ToArray()).ToArray();
string table = string.Join(",", headers) + Environment.NewLine;
foreach (string[] a in items)
{
table += string.Join(",", a) + Environment.NewLine;
}
table = table.TrimEnd('\r', '\n');
System.IO.File.WriteAllText(file.FileName, table);
}
}
so far i tried to autoformat my columns when data values are transferred to excel file but it doesn't go with this "lstResult.Columns.Autofit() why is it? because when i open my excel file it shows up that i have to resize each column base on the width of the data values been exported. please Help

Categories

Resources