I used this code to open the HTML page in HTML editor in c#.
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Multiselect =
false, ValidateNames = true, Filter = "HTML|*.html" })
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read);
webBrowser1.DocumentStream = fs;
}
}
and also I used this code to save the changes
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog svf = new SaveFileDialog();
svf.Filter = "Text Files (.html)|*.html";
if (svf.ShowDialog() == DialogResult.OK)
{
System.IO.StreamWriter sw = new System.IO.StreamWriter(svf.FileName);
sw.WriteLine(webBrowser1);
sw.Close();
}
}
However, the only line is saved in my HTML page is this message: System.Windows.Forms.WebBrowser.
Do you have any idea that how can I save the content of the HTML page? Thanks
The following should work as you require:
System.IO.StreamWriter sw = new System.IO.StreamWriter(svf.FileName);
webBrowser1.DocumentStream.CopyTo(sw.BaseStream);
sw.Flush();
sw.Close();
The reason yours does not work is because you're trying to write an object to a stream directly, which as stated implicitly calls the ToString() method.
Related
I'm new in C#, And I have tried many solutions but couldn't do it, this is my code , How to write this four (bytes) declared in first method but I want write them to file in second method.
private void openfiles()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open";
ofd.Filter = "Bin files|*.bin";
if (ofd.ShowDialog() == DialogResult.OK)
{
string path = ofd.FileName;
using (BinaryReader b = new BinaryReader(File.Open(path, FileMode.Open)))
{
long size = new System.IO.FileInfo(path).Length;
long ssize = new System.IO.FileInfo(path).Length / 1024;
int allsize = unchecked((int)size);
byte[] bytes = b.ReadBytes(4);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
using (BinaryWriter bw =new BinaryWriter(File.Open("FileName.bin",FileMode.Create)))
{
bw.Write(bytes);
bw.Close();
}
}
First you need to have somewhere to store the data after it is read and until it is written again. Best guess would be a field in the form, but that is design decision you need to make.
Next split up your code into functional parts, and don't put everything into button handlers. This way parts of the code can be re-used if needed.
Because the design intent is not clear, I have a very basic skeleton code below:
public partial class Form1 : Form
{
string _filename;
byte[] _data;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog();
dlg.Title = "Open";
dlg.Filter = "Bin files|*.bin";
if (dlg.ShowDialog() == DialogResult.OK)
{
this._filename = dlg.FileName;
this._data = ReadHeader(_filename);
MessageBox.Show($"Read {_data.Length} bytes from {_filename}");
}
}
private void button2_Click(object sender, EventArgs e)
{
string destination = "Filename.bin";
if (MessageBox.Show($"About to overwrite {destination} with data from {_filename}. Proceed?", "File Header", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
WriteHeader(destination, this._data);
}
}
static byte[] ReadHeader(string filename)
{
byte[] fileHeader;
var fs = File.OpenRead(filename);
using (var fr = new BinaryReader(fs))
{
fileHeader = fr.ReadBytes(4);
}
fs.Close();
return fileHeader;
}
static void WriteHeader(string filename, byte[] fileHeader)
{
var fs = File.OpenWrite(filename);
using (var fw = new BinaryWriter(fs))
{
fw.Write(fileHeader);
}
fs.Close();
}
}
Im trying to export data from gridview to .csv and saving it using save file dialog, but when i press the button, nothing happens. Gridview works correctly, here is the code:
public struct DataParameters
{
public List<Currency> currency;
public string Filename;
}
public static DataParameters dataParameters;
On button click - open file dialog export file to csv and save it
protected void Button1_Click(object sender, EventArgs e)
{
using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "CSV
files (*.csv)|*.csv|All files (*.*)|*.*" ,
ValidateNames = true, InitialDirectory = #"C:\",
RestoreDirectory = true, CheckFileExists = true, CheckPathExists
= true, DefaultExt = "csv" }) {
if (sfd.ShowDialog() == DialogResult.OK)
{
dataParameters.currency = GridView1.DataSource as
List<Currency>;
dataParameters.Filename = sfd.FileName;
}
}
List<Currency> currencies = dataParameters.currency;
string filename = dataParameters.Filename;
using (StreamWriter sw = new StreamWriter(new FileStream(filename,
FileMode.Create), Encoding.UTF8))
{
StringBuilder sb = new StringBuilder();
foreach (Currency c in currencies)
{
sb.AppendLine(string.Format($"{c.Drzava} {c.Sifra_valute} {
{c.Valuta} {c.Jedinica} {c.Kupovni_tecaj} {c.Srednji_tecaj}
{c.Prodajni_tecaj}"));
}
sw.Write(sb.ToString());
}
}
Nothing happens when i press the button
I am new to this so bear with me.
I am trying to create an application that can open a file, load it and then populate the data into a table.
I have managed to hardcode it to the test file I wanted but now need to be able to open any file of the same extension.
The code I have so far is included.
Appreciate if someone could point me in the right direction :)
Thanks, Jo
OpenFileDialog ofd = new OpenFileDialog();
private void Button3_Click(object sender, EventArgs e)
{
ofd.Filter = "evtx|*.evtx"; //Only allows evtx file types to be seen and opened
if (ofd.ShowDialog() == DialogResult.OK) //Opens the file dialog on button click
{
this.fileNameTextBox.Text = ofd.FileName;
saveFileNameTextBox.Text = ofd.SafeFileName;
}
}
private void loadFileButton_Click(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add("Level");
dt.Columns.Add("Logname");
dt.Columns.Add("Event ID");
dt.Columns.Add("Date and Time");
using (var reader = new EventLogReader(#"C:\Users\Jason\Desktop\Event logs\Security.evtx", PathType.FilePath))
{
EventRecord record;
while ((record = reader.ReadEvent()) != null)
{
using (record)
{
dt.Rows.Add(record.Level, record.LogName, record.RecordId, record.TimeCreated.Value.ToString("dd/MM/yyyy tt:hh:mm:ss"));
}
}
}
tblLogViewer.DataSource = dt;
}
If I understand what your issue is, you are prompting for a file in Button3_Click() with...
if (ofd.ShowDialog() == DialogResult.OK) //Opens the file dialog on button click
{
this.fileNameTextBox.Text = ofd.FileName;
saveFileNameTextBox.Text = ofd.SafeFileName;
}
...but then in loadFileButton_Click() you are using a different path to construct an EventLogReader...
using (var reader = new EventLogReader(#"C:\Users\Jason\Desktop\Event logs\Security.evtx", PathType.FilePath))
{
You are already saving the selected file's path to fileNameTextBox.Text, so just pass that property to the EventLogReader constructor instead...
using (var reader = new EventLogReader(fileNameTextBox.Text, PathType.FilePath))
{
Note that loadFileButton_Click assumes that ofd has previously been displayed and accepted (not canceled). Without knowing what your different buttons are, it might be better to create and use your EventLogReader immediately after successfully prompting for an input file...
if (ofd.ShowDialog() == DialogResult.OK) //Opens the file dialog on button click
{
this.fileNameTextBox.Text = ofd.FileName;
saveFileNameTextBox.Text = ofd.SafeFileName;
using (var reader = new EventLogReader(ofd.FileName, PathType.FilePath))
{
// Use reader...
}
}
I am creating a text editor and i am stuck on the SaveFileDialog window opening
and asking to overwrite the current file open.
I have seen all the similar questions asked like this on SO but none have been able to help me. I have even tried the code from this question: "Saving file without dialog" Saving file without dialog
I got stuck on my program having a problem with FileName.
Here is the code i have currently
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
open.Title = "Open File";
open.FileName = "";
if (open.ShowDialog() == DialogResult.OK)
{
this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
StreamReader reader = new StreamReader(open.FileName);
richTextBox1.Text = reader.ReadToEnd();
reader.Close();
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
save.Title = "Save File";
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(save.FileName);
writer.Write(richTextBox1.Text);
writer.Close();
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saving = new SaveFileDialog();
saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
saving.Title = "Save As";
saving.FileName = "Untitled";
if (saving.ShowDialog() == DialogResult.OK)
{
StreamWriter writing = new StreamWriter(saving.FileName);
writing.Write(richTextBox1.Text);
writing.Close();
}
}
}
}
So my question is how can i modify my code so that i can save a file currently open without having the SaveFileDialog box opening everytime?
I do understand that it has something to do with the fact that i'm calling .ShowDialog but i don't know how to modify it.
When opening the file, save the FileName in a form-level variable or property.
Now while saving the file, you can use this FileName instead of getting it from a FileOpenDialog.
First declare a variable to hold filename at form level
// declare at form level
private string FileName = string.Empty;
When opening a file, save the FileName in this variable
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
open.Title = "Open File";
open.FileName = "";
if (open.ShowDialog() == DialogResult.OK)
{
// save the opened FileName in our variable
this.FileName = open.FileName;
this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
StreamReader reader = new StreamReader(open.FileName);
richTextBox1.Text = reader.ReadToEnd();
reader.Close();
}
}
And when doing SaveAs operation, update this variable
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saving = new SaveFileDialog();
saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
saving.Title = "Save As";
saving.FileName = "Untitled";
if (saving.ShowDialog() == DialogResult.OK)
{
// save the new FileName in our variable
this.FileName = saving.FileName;
StreamWriter writing = new StreamWriter(saving.FileName);
writing.Write(richTextBox1.Text);
writing.Close();
}
}
The save function can then be modified like this:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.FileName))
{
// call SaveAs
saveAsToolStripMenuItem_Click(sender, e);
} else {
// we already have the filename. we overwrite that file.
StreamWriter writer = new StreamWriter(this.FileName);
writer.Write(richTextBox1.Text);
writer.Close();
}
}
In the New (and Close) function, you should clear this variable
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
// clear the FileName
this.FileName = string.Empty;
richTextBox1.Clear();
}
Create a new string variable in your class for example
string filename = string.empty
and then
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(filename)) {
//Show Save filedialog
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
save.Title = "Save File";
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (save.ShowDialog() == DialogResult.OK)
{
filename = save.FileName;
}
}
StreamWriter writer = new StreamWriter(filename);
writer.Write(richTextBox1.Text);
writer.Close();
}
The SaveFileDialog now only opens if fileName is null or empty
You will have to store the fact that you have already saved the file, e.g. by storing the file name in a member variable of the Form class you have. Then use an if to check whether you have already saved your file or not, and then either display the SaveFileDialog using ShowDialog() (in case you haven't) or don't and continue to save to the already defined file name (stored in your member variable).
Give it a try, do the following:
Define a string member variable, call it _fileName (private string _fileName; in your class)
In your saveToolStripMenuItem_Click method, check if it's null (if (null == _fileName))
If it is null, continue as before (show dialog), and after getting the file name, store it in your member variable
Refactor your file writing code so that you either get the file name from the file dialog (like before), or from your member variable _fileName
Have fun, C# is a great language to program in.
First, extract method from saveAsToolStripMenuItem_Click: what if you want add up a popup menu, speed button? Then just implement
public partial class Form1: Form {
// File name to save text to
private String m_FileName = "";
private Boolean SaveText(Boolean showDialog) {
// If file name is not assigned or dialog explictly required
if (String.IsNullOrEmpty(m_FileName) || showDialog) {
// Wrap IDisposable into using
using (SaveFileDialog dlg = new SaveFileDialog()) {
dlg.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
dlg.Title = "Save File";
dlg.FileName = m_FileName;
if (dlg.ShowDialog() != DialogResult.OK)
return false;
m_FileName = dlg.FileName;
}
}
File.WriteAllText(m_FileName, richTextBox1.Text);
this.Text = Path.GetFileNameWithoutExtension(m_FileName);
return true;
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) {
// SaveAs: always show the dialog
SaveText(true);
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e) {
// Save: show the dialog when required only
SaveText(false);
}
...
}
I'm using C# web browser and I want to save some of pages when a key is pressed but when I use SaveFileDialgue a window pop ups and asks for destination! Is there any way to save it directly to a specific destination without prompting me?
here it is my code:
private void btnSubmit_Click(object sender, EventArgs e)
{
browser.Navigate("https://www.google.com/");
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = " TEXT File |*.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
browser.SaveDocument(sfd.FileName);
}
}
remove the following lines
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = " TEXT File |*.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
browser.SaveDocument(sfd.FileName);
}
add
browser.SaveDocument("c:\\outputfile.txt");
You can read all the page using
private void BtnSaveHtml_Click(object sender, EventArgs e)
{
// webBrowser1.ShowSaveAsDialog();
string html;
html = webBrowser1.DocumentText.ToString();
}
and with the help of stream writer you save all the data where you want to save.