So I'm currently creating a quiz for coursework and originally I had all my questions inside of txt files. I am now in the process of putting the questions in one binary file. To make this easier upon myself I'm trying to make a converter button which will set a string variable to the path of the txt file but it just won't assign itself.
string file_name;
OpenFileDialog browse = new OpenFileDialog();
browse.Filter = "Choose Questions to import(*.txt;)|*.txt";
if (browse.ShowDialog() == DialogResult.OK)
{
file_name = browse.FileName;
}
System.IO.StreamReader txtReader;
txtReader = new System.IO.StreamReader(file_name);
The issue is that you should be doing all the code inside the OK portion.
Otherwise, if they cancel, it'll throw an error.
You also want to use a USING statement to read files so it disposes of resources.
browse.FileName works.
OpenFileDialog browse = new OpenFileDialog();
browse.Filter = "Choose Questions to import(*.txt;)|*.txt";
if (browse.ShowDialog() == DialogResult.OK)
{
string file_name = browse.FileName;
using (System.IO.StreamReader txtReader = new System.IO.StreamReader(file_name))
{
// Do Your File Manipulation Here!
}
}
Related
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.
I'm using C# to open a text file then I read everything inside it with this code:
OpenFileDialog pic = new OpenFileDialog();
pic.ShowDialog();
System.IO.StreamReader file = new System.IO.StreamReader(pic.OpenFile());
a=file.readline();
After I've finished reading, I want to read the data again but it tells me it's empty - how can I read it again?
Try something like this
var openDialog = new OpenFileDialog();
if (openDialog.ShowDialog == DialogResult.OK)
{
using (var stream = File.OpenRead(openDialog.FileName)
{
//read everything here
}
}
My guess is that the file only contains 1 line and so once you've read it there's nothing left to read. If you want to read the same line again you'll need to close the file and open it again. You should also be using a 'using' statement around the stream reader to ensure it is correctly disposed of, so something like:
string a = string.Empty;
using(StreamReader reader = new StreamReader(pic.FileName))
{
a = reader.ReadLine();
}
I want to create a browse (OpenFile Dialog) Button to search my local drive and then write out the selected file name (not the full path ) to a TextBox. It should show Only .dat extension files.
I am using Visual Studio 2008
Any help much appreciated!
Next time you ask anything, show some examples of what you have tried please.
private string GetDatFileName()
{
// Create Open File Dialog with the correct filter
using (OpenFileDialog ofd = new OpenFileDialog()) {
ofd.Filter = "dat-file (*.dat) | *.dat";
string fileNameAndFolder = "";
string fileName = "";
// Get file plus folder.
if (ofd.ShowDialog() == DialogResult.OK)
{
fileNameAndFolder = ofd.FileName;
// Split folder and filename
fileName = Path.GetFileName(fileNameAndFolder);
}
// Return the fileName;
return fileName;
}
}
What I have done here is create an OpenFileDialog and set its filter to the required "dat"-format. Only .dat-files will show up in the browserdialog.
Next, you show the dialog and check if the result is OK. If the result is, you will get the full filename (with folder) into a variable. All thats left then, is to get the filename from fileNameAndFolder.
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");
}
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