C#没有错误与警告,但有异常执行不了

img


想问一下,这怎么改啊


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace 实验1
{
    public partial class Form1 : Form
    {
        //定义random的上下限初始值,防止空指针异常随便写一个数,maxVAlue在后面会重新复制
        int minValue = 0;
        int maxValue = 54;
        Random r = new Random();

        //定义文件路径
        static string path = "Form1.txt";

        //读取文件的行数
        private int line_num()
        {
            
            string[] lines = File.ReadAllLines(path);
            int i = lines.Length;
            return i;
        }

        //随机时钟
        private void timer1_Tick(object sender, EventArgs e)
        {
            //设置随机数的上下限,标准规定的取值是,左闭右开
            string[] content = File.ReadAllLines(path);
            maxValue = line_num();
            int i = r.Next(minValue, maxValue);
            label1.Text = content[i];
            timer1.Start();
        }


        public Form1()
        {
            InitializeComponent();
        }




        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_Click(object sender, EventArgs e)
        {

        }

        //添加幸运儿按钮
        private void button1_Click(object sender, EventArgs e)
        {
            //在文件末尾追加一行
            FileStream fs = new FileStream(path, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            sw.WriteLine(textBox1.Text);
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
            label2.Text = "当前人数:" + line_num().ToString();
        }

        //抽奖开始结束按钮
        private void button2_Click(object sender, EventArgs e)
        {
            if (button2.Text == "开始")
            {
                button2.Text = "结束";
                timer1.Start();
            }
            else
            {
                button2.Text = "开始";
                timer1.Stop();
            }

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            label2.Text = "当前人数:" + line_num().ToString();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

e:\安装包\visual studio 2019作业\实验\实验1\bin\debug\netcoreapp3.1\form1.txt

你仔细看你的文件路径,你的这个报错,是文件路径不存在

在没有给定路径的情况下,在 release 时运行,他的默认路径是 e:\安装包\visual studio 2019作业\实验\实验1\bin\release\netcoreapp3.1\form1.txt

将变量path改成这样: static string path = Path.Combine(Application.StartupPath, "Form1.txt");
Application.StartupPath即程序根目录。