Unable to automatically save a file after reading it in. c# - c#

I am attempting to create a note taking application (first Windows Forms application). So far I have managed to read a .txt file into a RichTextBox. I am trying to make the program create and save the .txt file containing the contents of the .txt file that was read in read in. So when the user adds text from a file it creates a new file in a notes folders that is in the root directory of application. Please see my code below. Any advice would be greatly appreciated. Cheers
private void button1_Click(object sender, EventArgs e)
{
//read in a .txt file
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
string fileName = op.FileName;
//create new .txt file contaning module notes
System.IO.StreamWriter file = new System.IO.StreamWriter("\\"+fileName);
file.WriteLine(fileName);
file.Close();
}

Tested and working
//read in a .txt file
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
string fileName = Path.Combine(Application.CommonAppDataPath, Path.GetFileName(op.FileName));
File.WriteAllText(fileName, "test");

wrap your streams, files (anything that implements IDisposable) in a using block:
using(var myfile = File. CreateText(path) ) {
myfile.WriteLine("hi");
}
it's not creating a file because the path is wrong

Related

How to save a file that already exists?

I'm going to launch a code editor for people to create bots to disagree, it's almost all ready, but what I need help is when saving the file, I created a function that saves but when the file already exists the person have to replace, then I created a String called currentFile that will store the path of the selected file, then how do I make it just replace the text inside the file without needing to replace the file or open the save menu?
String currentFile = "C:\\Program Files (x86)\\EXAMPLE\\FILE.js";
SaveFileDialog sfd = default(SaveFileDialog);
if (fctb_code.Text.Length > 0)
{
sfd = new SaveFileDialog();
//sfd.Filter = "All Files|*.*";
//sfd.DefaultExt = "html";
sfd.ShowDialog();
string location = currentFile;
string sourcecode = fctb_code.Text;
location = sfd.FileName;
if (!object.ReferenceEquals(sfd.FileName, ""))
{
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(location, false))
{
writer.Write(sourcecode);
writer.Dispose();
}
}
And I want that when the file exists it just replaces the text inside the file, but when it doesn't exist it saves the file as a new one and opens SaveFileDialog.
All the code you have posted underneath sfd.ShowDialog(); can be replaced with one simple command (and an if statement)
if (sfd.FileName != "")
{
System.IO.File.WriteAllText(currentFile, fctb_code.Text);
}
No need for Streams and StreamWriters. No obtuse if logic.
To quote the documentation for File.WriteAllText, this will do overwriting for you:
Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

How do I download a file given the URL in C#

I am trying to download a file from a URL and I want to have a Popup where I can decide where to save the file on my pc. I know how to save it to a setlocation but that's not what I want.
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri("URL"), #"d:\location");
So I get that this is how I download it so a set location but I need to be able to save it to a location of choice with the usual popup you normally get when you download anything.
To give more sight into this I have 2 radiobuttonlists in which the user can check what topics he wants then he can choose from a dropdownlist which file he wants to download and then he click on a downloadbutton which should trigger the download of that file.
Use DownloadFileAsync and listen to DownloadFileFinished. First download it to temp file and at event DownloadFileFinished, show popup and ask where to save. Then just copy the file from temp file to the filename from user.
-or-
Show SaveFileDialog before you start DownloadFileAsync.
Talking about a desktop app you can use SaveFileDialog.
The msdn code example:
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}

Getting the path of a file from the SaveFileDialog to a string

In my form I have a button that launches the SaveFileDialog module. Then when I load a file, I want to save the path as a string and put that text into a text box on the form. I'm not sure how to do this, or even where to start?
Well the problem with your question is that you say when you "load a file", but you cannot load a file from the SaveFileDialog module. However, if you are opening a file via the OpenFileDialog module, then you are able to use this solution to get the directory path of the file you just loaded:
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
var directoryPath = Path.GetDirectoryName(openFileDialog1.FileName);
if(!string.IsNullOrEmpty(directoryPath))
textBox1.Text = directoryPath;
}
Otherwise, if you are wanting to get the file path of whatever file you saved originally, you can use pretty much the same solution to get the directory path:
if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
{
var directoryPath = Path.GetDirectoryName(saveFileDialog1.FileName);
if (!string.IsNullOrEmpty(directoryPath))
textBox1.Text = directoryPath;
}

Creating and saving files in C#

I need to create and write to a .dat file. I'm guessing that this is pretty much the same process as writing to a .txt file, but just using a different extension.
In plain english I would like to know how to:
-Create a .dat file
-Write to it
-And save the file using SaveFileDialog
There are a few pages that I've been looking at, but I think that my best explanation will come from this site because it allows me to state exactly what I need to learn.
The following code is what I have at the moment. Basically it opens a SaveFileDialog window with a blank File: section. Mapping to a folder and pressing save does not save anything because there is no file being used. Please help me use this to save files to different locations.
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "";
dlg.DefaultExt = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
}
Pages that I've been looking at:
-http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
-http://social.msdn.microsoft.com/Forums/en-US/cd0b129f-adf1-4c4f-9096-f0662772c821/how-to-use-savefiledialog-for-save-text-file
-http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx
Note that the SaveFileDialog only yields a filename but does not actually save anything.
var sfd = new SaveFileDialog {
Filter = "Text Files (*.txt)|*.txt|All files (*.*)|*.*",
// Set other options depending on your needs ...
};
if (sfd.ShowDialog() == true) { // Returns a bool?, therefore the == to convert it into bool.
string filename = sfd.FileName;
// Save the file ...
}
Use the filename you are getting from the SaveFileDialog and do the following:
File.WriteAllText(filename, contents);
That's all if you intend to write text to the file.
You can also use:
File.WriteAllLines(filename, contentsAsStringArray);
using(StreamWriter writer = new StreamWriter(filename , true))
{
writer.WriteLine("whatever your text is");
}

Text file doesn't get saved but no errors (C#)

I've been looking on many websites now for the answer, but all working answers only work for the richTextbox, and I'm using the normal textbox. I'm trying to save the contents of the textbox to a file of choice, but for some reason the file doesn't get saved, and I have no idea what the problem is. This is the code of the 'save' menu item:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog ofd = new SaveFileDialog();
ofd.Title = "Save";
ofd.Filter = "Txt Documents (.txt)|*.txt|All files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
//I don't know what to make of this, because clearly this doesn't work
File.WriteAllText(#"./TestFile.txt", MainTextbox.Text);
}
catch (Exception ex)
{
MainTextbox.Text += ex;
}
}
}
There is no error.
You should be saving to the file selected in your SaveFileDialog, as retrieved by OpenFile(). This example worked for me:
SaveFileDialog ofd = new SaveFileDialog();
ofd.Title = "Save";
ofd.Filter = "Txt Documents (.txt)|*.txt|All files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
using (var fileStream = ofd.OpenFile())
using (var sw = new StreamWriter(fileStream))
sw.WriteLine("Some text");
}
In your code, you let the user select a file to save to, then ignore that and write it to a hardcoded location. It's possible your app didn't have permissions to do this, but it should have permissions to write to a location the user selected.
First off, saving the file has nothing to do with where the text is coming from, rich text box or normal text box.
As Brian S. said in a comment, it is likely there is an exception because you're writing to the C drive. You should use a relative path: "./MyTest.txt"
I think its access denied issue.. try with 'D' drive ...
This is working example.. .WriteAllText works when file already exists and if file already exists then use AppendAllText
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
}
// This text is always added, making the file longer over time
// if it is not deleted.
string appendText = "This is extra text" + Environment.NewLine;
File.AppendAllText(path, appendText);
// Open the file to read from.
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}
Use a try { } catch (Exception ex) { } block How to: Use the Try/Catch Block to Catch Exceptions

Categories

Resources