Click here to Skip to main content
15,920,596 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
1.This is a code line:
StreamReader f=new StreamReader (cbIzborFile.Text+".txt");

2.This is Error message:
FileNotFoundException was unhandled
Could not find file 'C:\Users\user\Documents\Visual Studio 2010\Projects\Rad sa tekstualnim fajlom\Rad sa tekstualnim fajlom\bin\Debug\Rad sa tekstualnim fajlom.vshost.exe.txt'.
Type: System.IO.File.NotFoundException

Questions:
1.How do I eliminate mentioned error?
2.How to put textual files into directory Debug of my application or cite complete path of a textual files for using in my application?
Posted

Hi Member,

Althoug I think you won't learn much in programming if you don't try to solve your homework for yourself, it was fun for me to create a little sample application for you.
So maybe you find it interesting to see how I would approach the problem. The calculations you need to do a "crying" for a solution with LINQ - but if you have to avoid linq you can replace them with manual "looping".

Your current code has many "beginner" errors or is more complicated than needed. I didn't bother to "correct" it. Keep some simple rules in mind to make your live easier:

* Use proper variable names - f, s bp won't help you to understand what you have written - This is the most important thing in any kind of programming (no joke, I have decades of programming experience - just believe me) - find good names and use them!
* Don't do too much things "at once" - split your application in small, easy steps
* Use the Framework (or other existing code) so you don't have to "reinvent the wheel".

Long talk - short code: You can just copy following code to a new WindowsForms project (I used .NET 4.5.1), and replace the content of the pre-generated Program.cs file and let it run. For brevity I ommited the error handling (what if the file doesn't contain integers and so on - you'll have to do this for yourself if you want).

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace NumberFiles
{
    static class Program
    {
        /// <summary>
        /// This is the MainForm of the application. For demonstration purposes this Form is "designed" "in code" - normally you would use
        /// the visual Forms-Designer to create your Form.
        /// </summary>
        public class MainForm : Form
        {
            ListBox m_lbNumbers;
            Label m_labelResult;

            public MainForm()
            {
                // Adjust some Form-Properties
                Width = 640;
                Height = 480;

                // Create a ToolStrip to let the user trigger the needed functions
                ToolStrip ts = new ToolStrip();
                // ... with some ToolButtons
                ToolStripButton buttonOpenFile = new ToolStripButton { Text = "Open File" };
                buttonOpenFile.Click += buttonOpenFile_Click;
                ToolStripButton buttonGetMaximumNumber = new ToolStripButton { Text = "Max. Nr." };
                buttonGetMaximumNumber.Click += buttonGetMaximumNumber_Click;
                ToolStripButton buttonCountMaximumNumber = new ToolStripButton { Text = "Count Max. Nr." };
                buttonCountMaximumNumber.Click += buttonCountMaximumNumber_Click;
                ToolStripButton buttonCalculateAverage = new ToolStripButton { Text = "Calculate Average" };
                buttonCalculateAverage.Click += buttonCalculateAverage_Click;
                ToolStripButton buttonGetMaximumNumberOfSelectedNumbers = new ToolStripButton { Text = "Max. Nr. from Selection" };
                buttonGetMaximumNumberOfSelectedNumbers.Click += buttonGetMaximumNumberOfSelectedNumbers_Click;
                ts.Items.AddRange(new ToolStripItem[] { buttonOpenFile, buttonGetMaximumNumber, buttonCountMaximumNumber, buttonCalculateAverage, buttonGetMaximumNumberOfSelectedNumbers });

                // Create a ListBox to show the numbers (with enabled multi selection)
                m_lbNumbers = new ListBox { Dock = DockStyle.Fill, SelectionMode = SelectionMode.MultiExtended };

                // Create a Label to show the calculation results (with some initial text)
                m_labelResult = new Label { Dock = DockStyle.Bottom };

                // Add the Controls to this Form (order is important for the docking logic!)
                Controls.Add(m_lbNumbers);
                Controls.Add(ts);
                Controls.Add(m_labelResult);
            }

            void buttonOpenFile_Click(object sender, EventArgs e)
            {
                // Let the user choose a file
                OpenFileDialog ofd = new OpenFileDialog { Title = "Select a file containing numbers" };
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    // Read all lines from the text file selected by the user containing the numbers
                    string[] astrLines = File.ReadAllLines(ofd.FileName);

                    // Delete all current numbers from the list
                    m_lbNumbers.Items.Clear();

                    // Add the just read new numbers to the list 
                    foreach (string strLine in astrLines)
                        m_lbNumbers.Items.Add(Convert.ToInt32(strLine));
                }
            }

            // We use some LINQ for the calculations to make our live easy :-) 

            void buttonGetMaximumNumber_Click(object sender, EventArgs e)
            {
                IEnumerable<int> numbers = m_lbNumbers.Items.Cast<int>();
                int iMaxNr = numbers.Max();
                m_labelResult.Text = String.Format("Maximum number was {0}", iMaxNr);
            }

            void buttonCountMaximumNumber_Click(object sender, EventArgs e)
            {
                IEnumerable<int> numbers = m_lbNumbers.Items.Cast<int>();
                int iMaxNr = numbers.Max();
                int iCount = numbers.Count(n => n == iMaxNr);
                m_labelResult.Text = String.Format("Maximum number was {0}, it appears {1} times.", iMaxNr, iCount);
            }

            void buttonCalculateAverage_Click(object sender, EventArgs e)
            {
                IEnumerable<int> numbers = m_lbNumbers.Items.Cast<int>();
                double dAverage = numbers.Average();
                m_labelResult.Text = String.Format("Average of all numbers is {0}", dAverage);
            }

            void buttonGetMaximumNumberOfSelectedNumbers_Click(object sender, EventArgs e)
            {
                if(m_lbNumbers.SelectedItems.Count > 0)
                {
                    IEnumerable<int> numbers = m_lbNumbers.SelectedItems.Cast<int>();
                    int iMaxNr = numbers.Max();
                    m_labelResult.Text = String.Format("Maximum number of the selected numbers was {0}", iMaxNr);
                }
                else
                {
                    m_labelResult.Text = "No numbers selected, select at least two numbers";
                }
            }
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}


Feel free to ask any questions, I'll try to help - but as I said, nothing will prevent you from learning all the basics if you want to succed with software develpment.

Kind regards

Johannes
 
Share this answer
 
Comments
Member 9538830 25-Jul-14 9:54am    
Hi Johannes,

Thank you very much for your very professional reply.

I tested code that you send me and it works, although it is not meaning of my homework.

I should solve a many complex task. Could you see it and tell me how would I solve it?

Learning of the basics is particular and parallel process independent of this my task.

Sincerely Yours,
Zeljko Vujovic
1. use a valid path
2. copy the files where you need them. (or what was the question - google translate?)

Is this a serious question?
 
Share this answer
 
Comments
Member 9538830 23-Jul-14 10:57am    
Thank you. I am translating a book.
Your solution is correct. Yes, I used Google translate.

Could you help me to solve next errors, also, please?
Error 1 Embedded statement cannot be a declaration or labeled statement
Error 2 Use of unassigned local variable 'f'
Error 3 Expected class, delegate, enum, interface, or struct
Error 4 Use of unassigned local variable 'f'
Error 5 Type or namespace definition, or end-of-file expected
johannesnestler 23-Jul-14 13:32pm    
Hi Member,

It seems you are just beginning with .NET programming, I think the best advice would be to grab any C# book about the basics - the QA-Format wont help much if you haven't learned them (and the common error Messages you see if you do something wrong) In this case always look at the first error (meaning you using your variable f bevore you assigned it..), the other seem to be follow-up errors - eg. the last one just says you forgot a closing bracket). But post your code I will have a look.
Member 9538830 24-Jul-14 7:06am    
Here it is the task that I should to solve:

TASK:
Create application which shows content of a chose file in an object of the class ListBox and than application determines:
- maximal number,
- maximal number and number of its appearings,
- average value of numbers,
- maximal value of two seceded numbers.

Choice of the file name realize using object of the class ComoBox.

Supposition is that files have one number in each line.

TUTORIAL:
Set up next object on the form:
- object of the class ComoBox,
- object of the class ListBox,
- object of the class GroupBox,
(Set up four objects of the class RadioButto into
this class for execution of the tasks of application.)
- object of the class Label,
(for showing required results)

EXPLANATION:
Source code with mentioned errors is an attempt for solving the task.
Member 9538830 24-Jul-14 7:07am    
This is the Source Code:

using System;
using System.Windows.Forms;
using System.IO;

namespace Rad_sa_tekstualnim_fajlom_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void cbIzborFile_SelectedIndexChanged(object sender, EventArgs e)
{
if(cbIzborFile.Text!="Izaberi fajl")
StreamReader f=new StreamReader("C:\\Users\\user\\Documents\\Visual Studio 2010\\Projects\\Rad sa tekstualnim fajlom 1\\Rad sa tekstualnim fajlom 1\\bin\\Debug\\tekstualni fajl.txt");
String s;
lbBrojevi.Items.Clear();
s=f.ReadLine();
while(s!=null)
{
lbBrojevi.Items.Add(s);
s=f.ReadLine();
}
f.Close();
gbIzbor.Enabled=true;
lRezultat.Text="";
rbMax.Checked=rbMaxBrojPojavljivanja.Checked=
rbMaxRazlikaUzastopnih.Checked=rbProsjek.Checked=false;
}

private void Form1_Load(object sender, EventArgs e)
{

}
}

private void rbMax_CheckedChanged(object sender, EventArgs e)
{
if(rbMax.Checked)
{ StreamReader f=new StreamReader("C:\\Users\\user\\Documents\\Visual Studio 2010\\Projects\\Rad sa tekstualnim fajlom 1\\Rad sa tekstualnim fajlom 1\\bin\\Debug\\tekstualni fajl.txt");
String s;
int max,x;
s=f.ReadLine();
max=Convert.ToInt32(s);
s=f.ReadLine();
while(s!=null)
{
x=Convert.ToInt32(s);
if(x>max) max=x;
s=f.ReadLine();
}
f.Close();
lbRezultat.Text="Max broj je "+max;
}
private void rbMaxBrojPojavljivanja_CheckedChanged(object sender, EventArgs e)
{
StreamReader f = new StreamReader("C:\\Users\\user\\Documents\\Visual Studio 2010\\Projects\\Rad sa tekstualnim fajlom 1\\Rad sa tekstualnim fajlom 1\\bin\\Debug\\tekstualni fajl.txt");
String s;
int max, x, bp;
s = f.ReadLine();
max = Convert.ToInt32(s);
bp = 1;
s = f.ReadLine();
while(s!=null)
{
x=Convert.ToInt32(s);
if(x==max)
bp++;
else if(x>max)
{
max=x;
bp=1;
}
s=f.ReadLine();
}
f.Close();
lbRezultat.Text="Maksimalni broj je "+max+" pojavljuje se "+bp+" puta";
}
}
Member 9538830 24-Jul-14 7:11am    
And, here it is the content of the file named "tekstualni fajl.txt":

27
349
1583
-2431
90712
-78534

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900