How can I open a specific text file without using OpenFileDialog? - c#

I have a rich text editor that I have created in C#. One of the features I am now trying to add is templates. I do not want the user to have to use an OpenFileDialog to navigate to the template and open the file. I would like to specify the filepath myself so that the user only has to click one button in order to open the template.
Currently, I am trying to achieve this using the following code:
private void formalLetterToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
FileStream fileStream = new FileStream(#".\templates\tmp1.rtf", FileMode.Open);
String str;
str = fileStream.ToString();
string fileContents = File.ReadAllText(filepath);
fileContents = fileStream.ToString();
try
{
if (richTextBoxPrintCtrl1.Modified == true);
{
NewFile();
}
richTextBoxPrintCtrl1.Rtf = fileContents;
}
catch (Exception exception)
{
MessageBox.Show("There was an error opening the template. " + exception, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception exception)
{
MessageBox.Show("There was an error opening the template. " + exception, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
However, whenever I try to open the template, I get an exception that is as follows:
System.ArgumentsException: File format is not valid.
However, I have tried to open the file using my OpenFileDialog and that works fine. Could somebody assist me in getting this working correctly?

Your problem is that you're trying to convert the file to a string using str = fileStream.ToString(); however, this converts the filestream to a string which is not the same thing.
Instead just do string fileContents = File.ReadAllText(filepath); to get all of the files contents into a string. You only need to use a FileStream/StreamReader if you're going to do some type of processing on the file.
Also, your use of the FileStream is a little off. I think what you really want is a StreamReader with something like this (example from msdn);
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
A FileStream cannot be used to read a file. It must be passed to a StreamReader in order to actually read the file and in this case there is no point in doing that because there is an overload of the constructor which takes a filepath. It's only useful if you don't know what kind of stream the reader is going to be reading.
Where you have;
FileStream fileStream = new FileStream(#".\templates\tmp1.rtf", FileMode.Open);
String str;
str = fileStream.ToString();
string fileContents = File.ReadAllText(filepath);
fileContents = fileStream.ToString();
You actually just want thins line; string fileContents = File.ReadAllText(filepath); , nothing else. There is no need for a FileStream when you're just reading all the text into a string.

You are making very heavy weather of loading RTF. Your code to read a file into a string will never work, as #evanmcdonnal explained. Did your file dialog based code that succeeded really do it like that? Remember that a file dialog is just UI that generates a file name in a string. If your code with a file dialog works, then it will work when the file dialog is replaced with a hard coded string.
I suspect that some part of your problem is that you are using a relative path. Perhaps the working directory is not what you expect it to be. You should specify the full path to the file.
In any case, to load RTF simply call the LoadFile method of the control. But I strongly recommend passing the full path to the file.
richTextBoxPrintCtrl1.LoadFile(fullPathToRtfFile);

Related

Create a valid PDF from a web request

I'm trying to create a scanning solution. Basically the user is physically scanning a page. The printer is making an API call, passing in the binary data of the scan in the body.
I'm trying to save this as a PDF on the server, but when I go to open the file, i'm getting an error "There is an error while reading a stream".
var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
var bodyText = bodyStream.ReadToEnd();
string pathToFiles = HttpContext.Current.Server.MapPath("~\\UploadedFiles\\WriteLines.pdf");
try
{
using (StreamWriter outputFile = new StreamWriter(pathToFiles, false))
{
outputFile.WriteLine(bodyText);
}
HttpContext.Current.Response.ContentType = "application/pdf";
}
catch (Exception ex)
{
throw (ex);
}
This is just testing something, and I have permissions etc for writing the file, it's just not creating a valid file.
Any thoughts on what I should use? I have looked into some libraries, but they don't seem to cover what i'm after
StreamReader.ReadToEnd convert bytes to string in particular encoding (UTF8 by default). I don't think this work for PDF.
You need copy bytes directly in the output file :
var bodyStream = HttpContext.Current.Request.InputStream;
bodyStream.Seek(0, SeekOrigin.Begin);
string pathToFiles = HttpContext.Current.Server.MapPath("~\\UploadedFiles\\WriteLines.pdf");
using (FileStream outputFile = File.Create(pathToFiles))
{
bodyStream.CopyTo(outputFile);
}

How can I write and read a text doucument in a folder?

string curetn = Environment.CurrentDirectory;
string path = curetn.ToString() + #"\DATA\SaveGame.txt";
Console.WriteLine(path);
TextReader tr = new StreamReader(path);
Hello, I am making a text-adventure, and I do not like having all my save files, and mp3 file in the same place as my application. I would like for the files to be in a folder. I want to be able to use StreamWriter and StreamReader, to be able to write and read files that are in a folder. This file is also in a distributable folder, not just in the Visual Studios Projects folders. I have tried everything I can, and this is what I have. I also have one of these for StreamWriter. Please help!
Edit:
The thing that does not work, is that it does not read the lines, and assigns them to a variable. I have it in a try-catch, and it catches, and displays the error message that I wrote.
If you are looking for simply read and write lines from file you can try this
using (StreamReader sr = new StreamReader(path))
{
while (!sr.EndOfStream)
{
sr.ReadLine();
}
}
string s;
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(s);
}
So basically what you want to do is read the text file:
string data[] = File.ReadAllLines(path); // Read the text file.
var x = data[1]; // Replace the '1' with the line number you want.
Console.WriteLine(x);
This is a good way to read the text file, I think it's better than opening a stream.
You can also write to it, so every time you want to save, just do this:
// When you want to write:
File.WriteAllText(path, "");
File.AppendAllText(path, "Add a data line" + Environment.NewLine); // Environment.NewLine adds a line.
Keep appending text to the file for the data you need.

Catch "FileNotFoundException"

I have a method to get the folder path of a particular file:
string filePath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments), "file.txt");
And later, I use this to read the text in the file:
StreamReader rdr = new StreamReader(filePath); // "C:\Users\<user>\Documents\file.txt"
string myString = rdr.ReadToEnd();
Trouble is, if the file doesn't exist, it throws a FileNotFoundException (obviously). I want to hopefully use an if/else to catch the error, in which the user can browse to find the file directly, but I'm not sure what to use to verify if filePath is valid or not.
For example, I can't use:
if (filePath == null)
because the top method to retrieve the string will always return a value, whether or not it is valid. How can I solve this?
While File.Exists() is appropriate as a start, please note that ignoring the exception can still lead to an error condition if the file becomes inaccessible (dropped network drive, file opened by another program, deleted, etc.) in the time between the call to File.Exists() and new StreamReader().
You can use File.Exists:-
if(File.Exists(filePath))
{
//Do something
}
else
{
}
string filePath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments), "file.txt");
if(!File.Exists(filePath))
{
/* browse your file */
}
else
{
StreamReader rdr = new StreamReader(filePath); // "C:\Users\<user>\Documents\file.txt"
string myString = rdr.ReadToEnd();
}

Can't read file properly from windows notepad

I write some codes for simple text editor in C# and I use rich text box control, I found a problem that I can't solve. The problem is when I save a file in my text editor and then try to reopen it using windows notepad, it become in one line, this is the example
This is when I write and save from my app
After I save it and open in windows notepad it becomes like this
here are my code for saving a fie
try
{
saveFileDialog1.ShowDialog();
this.Text = file = toolStripTextBox1.Text = saveFileDialog1.FileName;
isi = richTextBox1.Text;
write = new System.IO.StreamWriter(file);
write.WriteLine(isi);
write.Close();
toolStripStatusLabel2.Text = "Saved";
}
catch (Exception)
{
toolStripStatusLabel2.Text = "Save cancelled by user";
}
do you have any idea how to fix it?
You are probably getting this because you are trying to save richTextBox1.Text (the whole text) in one line only using the following code
isi = richTextBox1.Text;
write = new System.IO.StreamWriter(file);
write.WriteLine(isi);
write.Close();
It's recommended to use write.WriteLine() on a specific line number in richTextBox1 then move to another line.
Example
for (int i = 0; i < richTextBox1.Lines.Length; i++)
{
write.WriteLine(richTextBox1.Lines[i]);
}
write.Close();
Another Solution
There's already a built-in function for RichTextBox to save a file with a specific encoding. You may use RichTextBox.SaveFile() for this purpose.
Example
RichTextBox.SaveFile(string path, RichTextBoxStreamType);
Where path represents saveFileDialog1.FileName in your code. For RichTextBoxStreamType, it's best to set it as RichTextBoxStreamType.PlainText as long as you do not use RTF such as Color/Font/Protection/Indent/etc...
Then, you may read the file again using the following method
RichTextBox.LoadFile(string path, RichTextBoxStreamType);
NOTICE: If the file is not in RTF and you try to read it in RTF (RichTextBox.LoadFile(string path, RichTextBoxStreamType.RichText);)
you may encounter formatting errors. In this case, you'll need to catch the exception and read the file in a Plain or Unicode encoding.
Example
RichTextBox _RichTextBox = new RichTextBox();
try
{
_RichTextBox.LoadFile(#"D:\Resources\text.txt", RichTextBoxStreamType.RichText);
}
catch (Exception EX)
{
if (EX.Message.ToLower().Contains("format is not valid"))
{
_RichTextBox.LoadFile(#"D:\Resources\text.txt", RichTextBoxStreamType.PlainText);
}
}
Thanks,
I hope you find this helpful :)
Saves the contents of the RichTextBox to a file by using richtextbox 's own save method: SaveFile(string, RichTextBoxStreamType);
you can refer this : http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.savefile%28VS.71%29.aspx
load the content of file by LoadFile(Stream, RichTextBoxStreamType);, refer this: http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.loadfile(v=vs.71).aspx

Sharing violation during save as on Ubuntu Linux

I'm new to C# and I'm having a bit of an issue when saving to a new file. My program has two options for saving: save & save as.
I was getting a sharing violation error when saving, but I fixed that by closing the previous filestream. However, I still cant figure out why my save as code is giving me a sharing violation error.
Here's the code:
// get a file stream from the file chooser
FileStream file = File.OpenWrite(saveFc.Filename);
// check to see if the file is Ok
bool fileOk = file.CanWrite;
if (fileOk == true)
{
// get the filename
string filename = file.Name;
// store the filename for later use
UtilityClass.filename = filename;
// get the text from textview1
string text = textview1.Buffer.Text;
// get a StreamWriter
StreamWriter writer = File.CreateText(filename);
// write to the file
writer.Write(text);
// close/save the file
writer.Close();
file.Close();
}
}
// close the file c
If you could help me figure it out that would be much appreciated. Thanks!
You're opening the same file twice:
FileStream file = File.OpenWrite(saveFc.Filename);
And:
string filename = file.Name;
StreamWriter writer = File.CreateText(filename);
Your code could probably be simplified to:
using (var writer = File.CreateText(saveFc.Filename))
{
// store the filename for later use
UtilityClass.filename = saveFc.Filename;
// get the text from textview1
string text = textview1.Buffer.Text;
// write the text
writer.Write(text);
}
If you open the file with CreateText/OpenWrite it will always be writeable (or an exception will be thrown). The using block will automatically close the writer when it exits.

Categories