How to use OpenFileDialog - c#

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

Related

Taking file input from OpenFileDialog

I looked around for an answer to this and couldn't find anything. All I need to do is take an input from a text file with multiple lines selected from an OpenFileDialog box. Here's a selection from my code:
if (theDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = theDialog.OpenFile()) != null)
{
using (myStream)
{
//I need this to take input given from OpenFileDialog
this.read_display.Text = input;
}
}
}
I'm probably just overlooking something really obvious, but I'm not sure.
If you want to get the text from stream, you can create a StreamReader instance and call method ReadToEnd().
string input;
using (StreamReader sr = new StreamReader(myStream))
{
input = sr.ReadToEnd());
}

browse.FileName doesn't set my string variable

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!
}
}

How To "Unaccess" A File So Other Parts Of The Program Can Access It

I had the following code dispersed throughout my program. However I always seem to get the error below. Even though I am using a "using bracket" to dispose of resources I still don't know why this is happening.
Error:
The Process cannot access the file "the file path" because it is being used by another process.
Code:
string folderpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "AGoogleHistory");
string filecreate;
private void restoreTbasToolStripMenuItem_Click(object sender, EventArgs e)
{
using(StreamReader sr = new StreamReader(filecreate))
{
string s = sr.ReadToEnd();
MessageBox.Show(s, "History", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
try
{
browser.Navigate(new Uri(Address));
using(StreamWriter sw = new StreamWriter(filecreate))
{
sw.WriteLine(Address);
}
}
catch(System.UriFormatException)
{
return;
}
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are You Sure", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
File.Delete(filecreate);
}
else
{
}
}
I think you should first check that file is exists or not by
File.Exists(filePath);
Second thing you are passing wrong parameter to StreamReader class which is an empty string as you haven't assigned anything to it. Check above mentioned things first and you can refer below link for your ease :
The process cannot access file...
Let me know if you have any other issue after trying this.
StreamReader, by default, locks the file. This causes the error you are seeing. Luckily, StreamReader accepts a stream as one of it's overloads for it's constructor. This allows you to first create a FileStream, which has a handy enum allowing you to specify read/write sharing, then pass that FileStream to your StreamReader for use.
So in your case:
using(StreamReader sr = new StreamReader(filecreate))
...
becomes:
FileStream fs = new FileStream(filecreate, FileMode.Open, FileShare.ReadWrite);
using(StreamReader sr = new StreamReader(fs))
...
For more info, see the question below. It's essentially the same question, just asked differently. The accepted answer should explain a bit more.
How to open a StreamReader in ShareDenyWrite mode?
EDIT
Looking over your question again, I see that part of your problem is you don't close your streams. They should get closed when the using block exits, but it's best practice to close them yourself with sr.Close();
Also, you may need to add the delete flag to the fileshare option:
FileStream fs = new FileStream(filecreate, FileMode.Open, FileShare.ReadWrite|FileShare.Delete);
using(StreamReader sr = new StreamReader(fs))
...

File in use error C# reading text from user specified file

My code is giving a runtime error that the file is in use already. I am not sure how I work around this. I need the file dialog to interact with the user but I want read through it line by line. the file is semicolon delimited and I parse it manually and feed it into the system. How can I release the file from opendialog so I can work with it. Any help much appreciated thanks in advance.
List<string> datalinestream = new List<string>();
FileDialog FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
TextReader reader = new StreamReader(FD.FileName);
using (reader)
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
while (!string.Equals(reader.Read(),"/r"))
{
datalinestream.Add(GetWord(reader));
}
LuceneDB.AddUpdateLuceneIndex(new MATS_Doc( datalinestream));
datalinestream.Clear();
}
}
}
What I'd do is I will create a temporary file that contains the same information of the original text file. I will make sure to format the filename with something like a GUID so it will not cause any issues again. My code then will do all of the work on the temporary file.
Afterwards, (if you need to) update the original file with the changes that you did on the temporary file.
Working with files sometimes is a headache but workarounds or tricking the system does the job.
I would suggest separating out the FileOpenDialog interaction from the parsing.
Something like this:
List<string> datalinestream = new List<string>();
string fileName;
using(FileDialog FD = new System.Windows.Forms.OpenFileDialog())
{
if(FD.ShowDialog() == DialogResult.OK)
fileName = FD.FileName;
else
return;
}
TextReader reader = new StreamReader(fileName);
using (reader)
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
while (reader.Read() != '\r')
{
datalinestream.Add(GetWord(reader));
}
LuceneDB.AddUpdateLuceneIndex(new MATS_Doc( datalinestream));
datalinestream.Clear();
}
}
I'm also assuming that you want to check for a \r character, instead of a string with the two characters / and r, as StreamReader.Read() returns a single character, otherwise your inner loop will have to change pretty drastically.

how to read the txt file from the database(line by line)

i have stored the txt file to sql server database .
i need to read the txt file line by line to get the content in it.
my code :
DataTable dtDeleteFolderFile = new DataTable();
dtDeleteFolderFile = objutility.GetData("GetTxtFileonFileName", new object[] { ddlSelectFile.SelectedItem.Text }).Tables[0];
foreach (DataRow dr in dtDeleteFolderFile.Rows)
{
name = dr["FileName"].ToString();
records = Convert.ToInt32(dr["NoOfRecords"].ToString());
bytes = (Byte[])dr["Data"];
}
FileStream readfile = new FileStream(Server.MapPath("txtfiles/" + name), FileMode.Open);
StreamReader streamreader = new StreamReader(readfile);
string line = "";
line = streamreader.ReadLine();
but here i have used the FileStream to read from the Particular path. but i have saved the txt file in byte format into my Database. how to read the txt file using the byte[] value to get the txt file content, instead of using the Path value.
Given th fact that you have the file in a byte array, you can make use of MemoryStream Class
Something like
using (MemoryStream m = new MemoryStream(buffer))
using (StreamReader sr = new StreamReader(m))
{
while (!sr.EndOfStream)
{
string s = sr.ReadLine();
}
}
Also make sure to use using Statement (C# Reference)
Defines a scope, outside of which an
object or objects will be disposed.
The using statement allows the
programmer to specify when objects
that use resources should release
them. The object provided to the using
statement must implement the
IDisposable interface. This interface
provides the Dispose method, which
should release the object's resources.
You could try something like this at the end of your foreach:
String txtFileContent = Encoding.Unicode.GetString((Byte[])dr["Data"]);

Categories

Resources