Click here to Skip to main content
15,923,006 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When I click the button everything workes until the using Stream writer part where the code crashes, how can I fix that?

Code 1:

C#
namespace Bankomat
{
    public partial class SättIn : Form
    {
        bool check = false;
        string[] hämtaSaldo;
        string line;
        public SättIn()
        {
            InitializeComponent();
        }

        private void btnTillbaka_Click(object sender, EventArgs e)
        {
            this.Hide();
            Alternativ alternativ = new Alternativ();
            alternativ.ShowDialog();
        }

        private void btnSättIn_Click(object sender, EventArgs e)
        {
            using (StreamReader reader = new StreamReader("Konto.txt"))
            {
                while ((line = reader.ReadLine()) != null)
                {
                    if (line.Contains(LoggaIn.användarnamn + "," + LoggaIn.lösenord))
                    {
                        check = true;
                        hämtaSaldo = line.Split(',');
                    }
                }
                reader.Close();
            }
            if (check)
            {
                using (StreamWriter writer = new StreamWriter("Konto.txt"))
                {
                    string nyttSaldo = (double.Parse(hämtaSaldo[2]) + double.Parse(txtBelopp.Text)).ToString();
                    line.Replace(hämtaSaldo[2], nyttSaldo);
                    writer.Close();
                }
            }
        }
    }
}


Code 2:

C#
namespace Bankomat
{
    public partial class LoggaIn : Form
    {
        public LoggaIn()
        {
            InitializeComponent();
        }

        private void btnTillbaka_Click(object sender, EventArgs e)
        {
            //Stänger formen LoggaIn och öppnar formen Startsida
            this.Hide();
            Startsida startsida = new Startsida();
            startsida.ShowDialog();
        }

        public static string användarnamn, lösenord;

        private void btnLoggaIn_Click(object sender, EventArgs e)
        {
            //Läser vare rad i filen Konto efter skrivet användarnamn och lösenord
            using (StreamReader reader = new StreamReader("Konto.txt"))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line.Contains(txtAnvändarnamn.Text + "," + txtLösenord.Text))
                    {
                        användarnamn = txtAnvändarnamn.Text;
                        lösenord = txtLösenord.Text;
                        //Stänger formen LoggaIn och öppnar formen Alternativ
                        this.Hide();
                        Alternativ alternativ = new Alternativ();
                        alternativ.ShowDialog();
                    }
                }
            }
        }
    }
}


Code 3:

C#
 namespace Bankomat
{
    public partial class SkapaKonto : Form
    {
        public SkapaKonto()
        {
            InitializeComponent();
        }

        private void btnTillbaka_Click(object sender, EventArgs e)
        {
            //Stänger formen SkapaKonto och öppnar formen Startsida
            this.Hide();
            Startsida startsida = new Startsida();
            startsida.ShowDialog();
        }

        private void btnSkapaKonto_Click(object sender, EventArgs e)
        {
            //Skriver ned det nya kontot i text filen Konto
            using (StreamWriter writer = new StreamWriter("Konto.txt"))
            {
                writer.WriteLine(txtAnvändarnamn.Text + "," + txtLösenord.Text + "," + "0");
                txtAnvändarnamn.Text = "";
                txtLösenord.Text = "";
            }
            //Visar användaren att kontot har skapats
            MessageBox.Show("Ditt konto har skapats!");
            //Stänger formen SkapaKonto och öppnar formen Startsida
            this.Hide();
            Startsida startsida = new Startsida();
            startsida.ShowDialog();
        }
    }
}


What I have tried:

I have tried searching in the code to find the error and then fix it but I can't really find it and I have also tried looking on the internet for solutions
Posted
Updated 14-Feb-20 3:28am
v2
Comments
Richard MacCutchan 14-Feb-20 5:41am    
Where does the error occur? You have three separate forms here, so you should at least know which one is active.
Severus Josefsen 14-Feb-20 6:02am    
The error occur in Code 1 and it is the StreamWriter
Richard Deeming 14-Feb-20 9:10am    
Looking at code 2, and guessing at the translations, it looks like you're storing a list of usernames and plain-text passwords in a text file.

That's an extremely bad idea - especially as the namespace suggests this is something to do with banking. You should only ever store a salted hash of the user's password:

Secure Password Authentication Explained Simply[^]
Salted Password Hashing - Doing it Right[^]

I can only hope that this is a toy application for a school project, and not something intended for real-world use!
Severus Josefsen 14-Feb-20 11:38am    
Well, This project is me learning StreamWriter and StreamReader only nothing else because that is what I learned during class.

1) Why are you opening a file for writing, but never writing to it?
C#
if (check)
{
    using (StreamWriter writer = new StreamWriter("Konto.txt"))
    {
        string nyttSaldo = (double.Parse(hämtaSaldo[2]) + double.Parse(txtBelopp.Text)).ToString();
        line.Replace(hämtaSaldo[2], nyttSaldo);
        writer.Close();
    }
}
2) In the above code fragment, line is guaranteed to be null because it can only ever exit the while loop above it when it is, so the Replace call will throw a NullReferenceException
3) Don't store (or try to write) data files in your program folder - and when you don't specify any folder, that's exactly where it is stored - as in production it is very likely to fail as it will be under "Program Files" and that is write protected to prevent or at least reduce virus activity. This may help: Where should I store my data?[^]
4) The problem you have met is probably not in that code: it's in the other code that accesses the file but which doesn't enclose the stream in a using block. I'd look through the rest of your code if I was you.
 
Share this answer
 
Comments
Severus Josefsen 14-Feb-20 2:56am    
I have uploaded the other codes
I'm guessing that you're trying to replace a line of text in a text file. There are two ways to do that.

Option 1:
Read the whole file into memory. Replace the line in the data you've read. Write the whole file out again.
C#
private void btnSättIn_Click(object sender, EventArgs e)
{
    string prefix = LoggaIn.användarnamn + "," + LoggaIn.lösenord + ",";
    bool found = false;
    
    string[] lines = File.ReadAllLines("Konto.txt");
    for (int index = 0; index < lines.Length; index++)
    {
        if (lines[index].StartsWith(prefix))
        {
            string[] parts = lines[index].Split(',');
            double oldValue = double.Parse(parts[2]);
            double belopp = double.Parse(txtBelopp.Text);
            double newValue = oldValue + belopp;
            parts[2] = newValue.ToString();
            lines[index] = string.Join(",", parts);
            found = true;
            break;
        }
    }
    
    if (found)
    {
        File.WriteAllLines("Konto.txt", lines);
    }
    else
    {
        // Notify the user that the line was not found...
    }
}
File.ReadAllLines Method (System.IO) | Microsoft Docs[^]
File.WriteAllLines Method (System.IO) | Microsoft Docs[^]

Option 2:
If the file is too large to read into memory, you'll need to copy it line-by-line to another file, and then replace the original:
C#
private void btnSättIn_Click(object sender, EventArgs e)
{
    string prefix = LoggaIn.användarnamn + "," + LoggaIn.lösenord + ",";
    bool found = false;
    
    using (var reader = new StreamReader("Konto.txt"))
    using (var writer = new StreamWriter("Konoto.tmp"))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            if (found || !line.StartsWith(prefix))
            {
                writer.WriteLine(line);
            }
            else
            {
                string[] parts = line.Split(',');
                double oldValue = double.Parse(parts[2]);
                double belopp = double.Parse(txtBelopp.Text);
                double newValue = oldValue + belopp;
                parts[2] = newValue.ToString();
                writer.WriteLine(string.Join(",", parts));
                found = true;
            }
        }
    }
    
    if (found)
    {
        // Overwrite the file with the updated file:
        File.Delete("Konoto.txt");
        File.Move("Konoto.tmp", "Konoto.txt");
    }
    else
    {
        // No changes - delete the temp file:
        File.Delete("Konoto.tmp");
    }
}


NB: As I mentioned in the comments, it looks like you're storing a list of usernames and plain-text passwords in this text file. This is a very bad idea, and is not suitable for any real-world application. You should only ever store a salted hash of the user's password; and you should really be using a database instead of a text file.
 
Share this answer
 

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