Read file problem - c#

I can't find a solution for this problem:
I write a program, which reads all file in a directory and puts them in a listbox.
When a user select a file from a listbox, the program reads the selected file and prints out some info...
The problem is that after the firs selection my program "stop working". He don't crash, but when I try to select another file he do nothing.
I figured out, that the problem is in:
private String porocilo(String s)
{
file = "/path to file/";
TextReader tr = new StreamReader(file); //<- problem here
//...
tr.close();
return someinfo;
}
//..
//Call function:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = porocilo(listBox1.SelectedItems[0].ToString());
}
After removing that (problem) line the program normally select files, but without this I can't read files and my program don't do anything.
Can someone tell me where I'm wrong?
Br, Wolfy

If the code you posted is really the code you are using (plus the missing semicolon), then the reason you are not seeing anything happening is because your code keeps opening and reading the same file, not the file the user selected. You are setting file to a constant path/filename and read from that, and you are not making use of the s parameter.

It looks like you have a hard-coded path in your porocilo method. That is, new StreamReader is taking as it's argument, file, not s.
So it will only ever open, one file, not the file you selected.
private String porocilo(String s)
{
//file = "/path to/file" // not sure what this is...???
TextReader tr = new StreamReader(s); //<- fix here
//...
tr.close();
return someinfo;
}

In your List box Selected index change method you need to assign the selected value as shown below
//Call function:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = porocilo(listBox1.SelectedItem.Text);
}
Also check your "porocilo" function it uses the parameter corectly

Related

How to display a random image from a list, everytime the button is pressed ? C#

So I'm totally new to C# and I've been building a "Character Generator" for a tabletop RPG. I've assigned a button with the task of generating a new story every time it is pressed. I've downloaded a huge collection of character portraits which I'd like to display in this little app of mine to give some inspiration to the user.
I thought that using a button I could have the app select a different image in the aforementioned list every time it is pressed.
I tried this:
private void button1_Click(object sender, EventArgs e)
{
List<String> paths = new List<String>();
Random random = new Random();
paths.Add(Project1.Cartes.Portrait);
pictureBox1.ImageLocation = paths[random.Next(0, images.Count - 1)];
I get two errors: Project1.Cartes.Portrait is an invalid namespace, and the name "images" does not exist.
I can't mention every image, since there are 500 of them. So I need the app to instead take a random image from a specific location. Any ideas ?
There is insufficient code be definite, however, the errors do indicate exactly what's wrong. For example, where is the variable images defined, what type is it, and how it is initialised? Also, I assume that Project1.Cartes.Portrait is meant to be a list of paths to the images and should there for be defined as List<string> somewhere within the current namespace.
As I noted in my comment, I think the Project1.Cartes.Portrait is not what you expect it to be. It should be a List<string> to any image files on your disk but it might add the string representation to your paths list.
Something like:
System.Collections.Generic.List1[System.String] (which is definitively not a path to an image file)
instead of the expected:
C:\mypath1.jpg
C:\mypath2.jpg
C:\mypath3.jpg
So please stop the debugger with a breakpoint after paths.Add(Project1.Cartes.Portrait) and check if your variable paths is what you expect it to be.
Btw, if Project1.Cartes.Portraitpoints to a real List<string>, you should use paths.AddRange(...) instead of paths.Add(...) to add the string contents from the list instead of the list itself.
Store the image's locations while your form is loading. Also, you need to remove image use bellow instead.
pictureBox1.ImageLocation = paths[random.Next(0, paths.Count - 1)];
Here is the full code. Just need to store the file names in the list.
List<String> paths = new List<String>();
private List<string> GetPaths()
{
//You can get it anywhere
throw new NotImplementedException();
}
private void Form1_Load(object sender, EventArgs e)
{
paths = GetPaths();
}
private void button1_Click(object sender, EventArgs e)
{
Random random = new Random();
pictureBox1.ImageLocation = paths[random.Next(0, paths.Count - 1)];
}

Can't delete the file after displaying on printpreviewcontroller

I have a print form which does the printing jobs.
When I close the print form without printing I click Close button
Close button has
private void Close_Click(object sender, EventArgs e)
{
PublicVariables.PrintData = -1;
PublicVariables.PrintStat = false;
ppc.Document = null;
ppc.Dispose();
streamToRead.Close();
this.Hide();
}
But each time I create a text file to print I delete the old.
Delete method :
public static bool DeleteData()
{
bool result=true;
string pattern = "data??.txt";
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
var matches = Directory.GetFiles(appPath, pattern);
foreach (string file in Directory.GetFiles(appPath).Intersect(matches))
{
try
{
File.Delete(file);
result =true;
}
catch (IOException e1)
{
MessageBox.Show(e1.ToString());
return false;
}
}
return result;
}
But if an IOException occurs can't delete any file.
However form load of all threads I have DeleteData() and this deletes without problem the text data.
Is there a way to delete this text file within in the thread where it's created ?
For those who will advise me to make an hidden form which will delete data. I did it I got always an IOexception error. After few IOexception errors all data??.txt files are erased but it happens randomly.
Here below two procedures which create data??.txt
http://www.turcguide.com/stack/procedures.txt
Here is the CreateDataFile(string fName) and GetNewfName(string oldName) procedures link:
http://turcguide.com/stack/createdatafile.txt
The printpreviewcontroler should block this file as when we cancel a printing document on printer it needs time.
After closing and disposing the printpreviewcontroller form, when I try to delete 4-5 attempts later the file is deleted.
My point of view it comes from printpreviewcontroller.

Doubleclick on saved file open my windows form but don't pick up any saved data

I created simple program for save/open practice. Made a setup and associated my program with my own datatype, called it .xxx (for practice).
I managed to Save and Open code and data from textbox but only from my program. Double click (or enter from windows-desktop) open up my WindowsForm as it is but there is an empty textbox. I want my saved file to be opened on double click in the same condition as when I open it from my program. How to set that up??
Here is the code of simple app (cant post images but it simple - got 1 label and 1 textbox with open and save buttons):
private void ButOpen_Click(object sender, EventArgs e)
{
textBox1.Text = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string data = Read(openFileDialog1.FileName);
textBox1.Text = data;
}
else
{//do nothing }
}
private string Read(string file)
{
StreamReader reader = new StreamReader(file);
string data = reader.ReadToEnd();
reader.Close();
return data;
}
private void ButSave_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Something|*.xxx";
DialogResult result = saveFileDialog1.ShowDialog();
string file = saveFileDialog1.FileName.ToString();
string data = textBox1.Text;
Save(file, data);
}
private void Save(string file, string data)
{
StreamWriter writer = new StreamWriter(file);
writer.Write(data);
writer.Close();
}
NOTE:
My similar question was marked as duplicate but it is not, and this question which was referenced as duplicate Opening a text file is passed as a command line parameter does not help me.It's not the same thing...
Just wanted to find out how to configure registry so windows understand and load data inside the file, or to file save data somehow so i can open it with double click.
So someone please help. If something is not clear I will give detailed information just ask on what point.
Thanks
MSDN has some information about this:
https://msdn.microsoft.com/en-us/library/bb166549.aspx
Basically you need to create an entry in the registry so that explorer.exe knows to launch your program when that file is activated (e.g. double-clicked).
Explorer will then pass the path to the file as an argument to your program.

Making a button that saves lists for the next time the program is run

I'm making a windows form application. It is a word generator that generates a random word from a default list that can also be modified by user input. I'm looking for a way to make it so that a button will save the lists so that the next time the user runs the application, they will have the same lists from before. txtaddverb is the text box for user input. The missing buttons do the same thing only for a list of nouns, adjectives, and adverbs.
Here is what my code looks like:
public class Lists
{
public static List<string> verbList = new List<string>() {"eat", "scramble", "slap", "stimulate"};
public static Random randomverb = new Random();
}
public string pickRandomVerb()
{
return Lists.verbList[Lists.randomverb.Next(0, Lists.verbList.Count)];
}
public void button1_Click(object sender, EventArgs e)
{
if (Lists.verbList.Count > 0) verb.Text = pickRandomVerb();
}
public void button5_Click(object sender, EventArgs e)
{
Lists.verbList.Add(txtaddverb.Text);
txtaddverb.Clear();
}
public void button9_Click(object sender, EventArgs e)
{
Lists.verbList.Clear();
verb.Clear();
txtaddverb.Clear();
}
//below is the button that I want to save the list
public static void button13_Click(object sender, EventArgs e)
{
//need help here
}
Depends. Where do you want to save the input? In a text-file? In a database?
Example of saving to a textfile
// create a writer and open the file
TextWriter tw = new StreamWriter("date.txt");
// write a line of text to the file
tw.WriteLine(DateTime.Now);
// close the stream
tw.Close();
To write a List<string> into a file:
File.WriteAllLines(path, verbList);
This will create the file if it doesn't exist or overwrite it otherwise.
Read it from the file:
List<string> verbList = File.ReadAllLines(path).ToList();
If this project is more for personal use then you could just write the list to a text file and read it back in when the program loads. The streamreader and streamwriter classes could be implemented for that. See http://msdn.microsoft.com/en-us/library/aa903247%28v=vs.71%29.aspx for some sample code.
If multiple people will be using your app, I'd say saving the list to a database would be a better solution. Here's a good place to start http://www.dreamincode.net/forums/topic/31314-sql-basics-in-c%23/#/ If you don't have SQL server the tutorial can be adjusted for something like MS Access. (you'd be using System.Data.OleDb instead of System.Data.SqlClient)
There are a lot of articles out there going over reading and writing information to text files or databases. Do a little searching and you should be able to find something that suits your needs if the two links I posted don't have what you're looking for.

Getting filesize from OpenFileDialog?

How can I get the filesize of the currently-selected file in my Openfiledialog?
You can't directly get it from the OpenFieldDialog.
You need to take the file path and consturct a new FileInfo object from it like this:
var fileInfo = new FileInfo(path);
And from the FileInto you can get the size of the file like this
fileInfo.Length
For more info look at this msdn page.
Without interop and like the first comment, once the dialogue has been complete i.e. file/s have been selected this would give the size.
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (openFileDialog1.Multiselect)
{
long total = 0;
foreach (string s in openFileDialog1.FileNames)
total += new FileInfo(s).Length;
MessageBox.Show(total.ToString());
}
else
{
MessageBox.Show(new FileInfo(openFileDialog1.FileName).Length.ToString());
}
}
}
File size during dialogue I feel would need to use interop
Andrew
I think there is 3 way, creating your custom open dialog or setting by code the view as detail or asking the user to use detail view
If you mean when the dialog is running, I suspect you just change the file view to details. However if you mean programmatically I suspect that you'd have to hook a windows message when the file is selected.

Categories