C#基础学习笔记(十四)

C#基础学习笔记(十四)

一、Directory操作文件夹

  • CreateDirectory 创建文件夹

  • Delete 删除文件夹

  • Move 剪切文件夹

  • Exist 判断是否存在

  • GetFiles 获得指定的目录下所有文件的全路径

  • GetDirectory 获得指定目录下所有文件夹的全路径

static void Main(string[] args)
{
    File Path FileStream StreamReader StreamWriter
    Directory文件夹目录

    //创建文件夹
    Directory.CreateDirectory(@"D:\C#\peixun\Day15\a");
    Console.WriteLine("创建成功");

    //删除文件夹
    //true要确定是否删除a文件夹下内的东西
    Directory.Delete(@"D:\C#\peixun\Day15\a", true);
    Console.WriteLine("删除成功");

    //剪切
    Directory.Move(@"D:\C#\peixun\Day15\a\b", @"D:\DownLoad");
    Console.WriteLine("剪切成功");

    //获得指定文件夹下所有文件的全目录,可以筛选文件类型
    string[] path = Directory.GetFiles(@"D:\示例图片", "*.jpg");
    for (int i = 0; i < path.Length; i++)
    {
        Console.WriteLine(path[i]);
    }

    //获得所有文件夹的目录
    string[] path = Directory.GetDirectories(@"D:\C#\peixun\Day15");
    for (int i = 0; i < path.Length; i++)
    {
        Console.WriteLine(path[i]);
    }

    //判断文件是否存在
    if (Directory.Exists(@"D:\C#\peixun\Day15\a"))
    {
        for (int i = 0; i < 10; i++)
        {
            Directory.CreateDirectory(@"D:\C#\peixun\Day15\a" + i);
        }
    }
    Console.WriteLine("创建成功");
    Console.ReadKey();
}

二、WebBrowser浏览器控件

在这里插入图片描述

private void button1_Click(object sender, EventArgs e)
{          
    string text = textBox1.Text;
    Uri uri = new Uri("http://" + text);
    webBrowser1.Url = uri;
}

三、ComboBox下拉框控件

DropDownStyle:控制下拉框的外观样式
名字:cbo+…
案例:日期选择器

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

    private void Form1_Load(object sender, EventArgs e)
    {
        //程序加载的时候 将年份添加到下拉框
        //获取当前的年份
        int year = DateTime.Now.Year;
        for (int i = year; i >= 1949; i--) 
        {
            cboYear.Items.Add(i + "年");
        }
    }

    private void cboYear_SelectionChangeCommitted(object sender, EventArgs e)
    {

    }
    /// <summary>
    /// 当年份发生改变的时候 加载月份
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        //但是点一次就会添加移除
        //添加之前应该清空之前的内容
        cboMonth.Items.Clear();
        for (int i = 1; i <= 12; i++) 
        {
            cboMonth.Items.Add(i + "月");
        }
    }
    /// <summary>
    /// 当月份发生改变的时候 加载天
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
    {
        cboDay.Items.Clear();
        int day = 0;
        //获得月份 7月
        string strMonth = cboMonth.SelectedItem.ToString().Split(new char[] { '月' }, StringSplitOptions.RemoveEmptyEntries)[0];
        string strYear = cboYear.SelectedItem.ToString().Split(new char[] { '年' }, StringSplitOptions.RemoveEmptyEntries)[0];
        int year = Convert.ToInt32(strYear);
        int month = Convert.ToInt32(strMonth);
        switch (month)
        {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                day = 31;
                break;
            case 2:
                if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
                {
                    day = 29;
                }
                else
                {
                    day = 28;
                }
                break;
            default:
                day = 30;
                break;
        }
        for (int i = 1; i <= day; i++)
        {
            cboDay.Items.Add(i + "日");
        }
    }
}

四、ListBox

1)、在程序加载的时候,将指定图片文件夹中所有的图片文件名读取到ListBox中

在这里插入图片描述

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    //用来存储图片文件的全路径
    List<string> list = new List<string>();
    private void Form1_Load(object sender, EventArgs e)
    {
        string[] path = Directory.GetFiles(@"D:\示例图片", "*.jpg");

        for (int i = 0; i < path.Length; i++) 
        {
            //listBox1.Items.Add(path[i]);
            string fileName = Path.GetFileName(path[i]);
            listBox1.Items.Add(fileName);
            //将图片的全路径添加到list里边
            list.Add(path[i]);
        }
    }
    /// <summary>
    /// 双击播放图片
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void listBox1_DoubleClick(object sender, EventArgs e)
    {
        pictureBox1.Image = Image.FromFile(list[listBox1.SelectedIndex]);
    }
}

2)点击播放音乐
在这里插入图片描述

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    List<string> listSong = new List<string>();
    private void Form1_Load(object sender, EventArgs e)
    {
        string[] path = Directory.GetFiles(@"D:\示例图片", "*wav");
        for (int i = 0; i < path.Length; i++)
        {
            string fileName = Path.GetFileName(path[i]);
            listBox1.Items.Add(fileName);
            listSong.Add(path[i]);
        }
    }

    private void listBox1_DoubleClick(object sender, EventArgs e)
    {
        SoundPlayer sp = new SoundPlayer();
        sp.SoundLocation = listSong[listBox1.SelectedIndex];
        sp.Play();
    }
}

五、石头剪刀布

石头 1 剪刀 2 布 3
玩家赢了: 1 2=-1 2 3=-1 3 1=2
平手: 相减 =0
另外一种情况 :电脑赢了

玩家——出拳的方法

电脑——出拳的方法

判断——

在这里插入图片描述

主窗体:

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

    private void btnStone_Click(object sender, EventArgs e)
    {
        string str = "石头";
        PlayGame(str);
    }
    private void btnCut_Click(object sender, EventArgs e)
    {
        string str = "剪刀";
        PlayGame(str);
    }

    private void btnNo_Click(object sender, EventArgs e)
    {
        string str = "布";
        PlayGame(str);
    }
    private void PlayGame(string str)
    {
        lblPlayer.Text = str;

        Player player = new Player();
        int playerNumber = player.ShowFist(str);

        Computer cpu = new Computer();
        int cpuNumber = cpu.ShowFist();
        lblComputer.Text = cpu.Fist;

        Result res = CaiPan.Judge(playerNumber, cpuNumber);

        lblResult.Text = res.ToString();
    }
}

Player类:

class Player
{
    public int ShowFist(string fist)
    {
        int num = 0;
        switch (fist)
        {
            case "石头":
                num = 1;
                break;
            case "剪刀":
                num = 2;
                break;
            case "布":
                num = 3;
                break;
        }
        return num;
    }
}

Computer类:

class Computer
{
    public string Fist { get; set; }

    public int ShowFist()
    {
        //只有展示随机数的,但是没有存储出东西的地方 定义一个字段
        Random r = new Random();
        int rNumber = r.Next(1, 4);
        switch (rNumber)
        {
            case 1:
                this.Fist = "石头";
                break;
            case 2:
                this.Fist = "剪刀";
                break;
            case 3:
                this.Fist = "布";
                break;
        }
        return rNumber;
    }
}

CaiPan类:

public enum Result
{
    玩家赢,
    电脑赢,
    平手
}
class CaiPan
{
    //只是单纯想要一个结果 写成静态类
    public static Result Judge(int playerNumber,int cpuNumber)
    {
        if (playerNumber - cpuNumber == -1 || playerNumber - cpuNumber == 2)
        {
            return Result.玩家赢;
        }
        else if (playerNumber - cpuNumber == 0) 
        {
            return Result.平手;
        }
        else
        {
            return Result.电脑赢;
        }
    }
}

六、对话框

1)打开对话框

在这里插入图片描述

private void button1_Click(object sender, EventArgs e)
{
    //点击弹出对话窗口
    OpenFileDialog ofd = new OpenFileDialog();
    //设置对话框的标题
    ofd.Title = "选择打开文件";
    //设置对话框可以多选
    ofd.Multiselect = true;
    //设置对话框需要打开的文本文件
    ofd.InitialDirectory = @"D:\示例图片";
    //设置对话框的文件类型
    ofd.Filter = "文本文件|*.txt|媒体文件|*.wav|图片工具|*.jpg|所有文件|*.*";
    //显示对话框
    ofd.ShowDialog();
    //获得打开对话框选中文件的路径
    string path = ofd.FileName;
    if (path == "") return;
    using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read)) 
    {
        byte[] buffer = new byte[1024 * 1024 * 5];
        //实际读取到的字节数
        int r = fsRead.Read(buffer, 0, buffer.Length);
        textBox1.Text = Encoding.Default.GetString(buffer, 0, r);
    }
}

2)保存对话框

在这里插入图片描述

private void button1_Click(object sender, EventArgs e)
{
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Title = "请选择想要保存的路径";
    sfd.InitialDirectory = @"D:\示例图片";
    sfd.Filter = "文本文件|*.txt|所有文件|*.*";
    sfd.ShowDialog();
    //获得保存的路径
    string path = sfd.FileName;
    if (path == "") 
    {
        return;
    }
    using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) 
    {
        byte[] buffer = Encoding.Default.GetBytes(textBox1.Text);
        fsWrite.Write(buffer, 0, buffer.Length);
    }
    MessageBox.Show("保存成功");
}

3)字体颜色对话框

在这里插入图片描述

private void button1_Click(object sender, EventArgs e)
{
    //字体
    FontDialog fd = new FontDialog();
    fd.ShowDialog();
    textBox1.Font = fd.Font;
}

private void button2_Click(object sender, EventArgs e)
{
    //颜色
    ColorDialog cd = new ColorDialog();
    cd.ShowDialog();
    textBox1.ForeColor = cd.Color;
}

4)记事本程序

文件——打开,保存

格式——自动换行

样式——字体,颜色

打开记录——显示和隐藏左侧历史记录

左侧可以隐藏,使用panel的可见

在这里插入图片描述

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

    private void Form1_Load(object sender, EventArgs e)
    {
        //加载程序的时候隐藏panel
        panel1.Visible = false;
        //取消文本框的自动换行功能
        textBox1.WordWrap = false;
    }
    private void button1_Click(object sender, EventArgs e)
    {
        panel1.Visible = false;
    }
    private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        panel1.Visible = true;
    }

    private void 隐藏ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        panel1.Visible = false;
    }

    private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Title = "请选择要打开的文本文件";
        openFileDialog.InitialDirectory = @"D:\示例图片";
        openFileDialog.Multiselect = true;
        openFileDialog.Filter = "文本文件|*.txt|所有文件|*.*";
        openFileDialog.ShowDialog();
        //获得用户选中的文件路径
        string path = openFileDialog.FileName;
        //将文件存到list里边
        list.Add(path);
        //获得用户打开文件的文件名
        string fileName = Path.GetFileName(path);
        //将文件名放到listbox中
        listBox1.Items.Add(fileName);
        if (path == "") 
        {
            return;
        }
        using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read)) 
        {
            byte[] bufer = new byte[1024 * 1024 * 5];
            int r = fsRead.Read(bufer, 0, bufer.Length);
            textBox1.Text = Encoding.UTF8.GetString(bufer, 0, r);
        }
    }

    private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        SaveFileDialog saveFileDialog = new SaveFileDialog();
        saveFileDialog.InitialDirectory = @"D:\示例图片";
        saveFileDialog.Title = "请选择保存的文本文件";
        saveFileDialog.Filter = "文本文件|*.txt|所有文件|*.*";
        saveFileDialog.ShowDialog();
        //获得用户要保存的文件的路径
        string path = saveFileDialog.FileName;
        if (path == "") 
        {
            return;
        }
        using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) 
        {
            byte[] buffer = Encoding.UTF8.GetBytes(textBox1.Text);
            fsWrite.Write(buffer, 0, buffer.Length);
        }
        MessageBox.Show("保存成功");
    }

    private void 自动换行ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (自动换行ToolStripMenuItem.Text == "自动换行") 
        {
            textBox1.WordWrap = true;
            自动换行ToolStripMenuItem.Text = "取消自动换行";
        }
        else if (自动换行ToolStripMenuItem.Text == "取消自动换行")
        {
            textBox1.WordWrap = false;
            自动换行ToolStripMenuItem.Text = "自动换行";
        }
    }

    private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FontDialog fontDialog = new FontDialog();
        fontDialog.ShowDialog();
        textBox1.Font = fontDialog.Font;
    }

    private void 颜色ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        ColorDialog colorDialog = new ColorDialog();
        colorDialog.ShowDialog();
        textBox1.ForeColor = colorDialog.Color;
    }

    List<string> list = new List<string>();
    private void listBox1_DoubleClick(object sender, EventArgs e)
    {
        //双击listbox打开对应的文件
        string path = list[listBox1.SelectedIndex];
        using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read)) 
        {
            byte[] buffer = new byte[1024 * 1024 * 5];
            int r = fsRead.Read(buffer, 0, buffer.Length);
            textBox1.Text = Encoding.UTF8.GetString(buffer, 0, r);
        }
    }
}

七、进程

我们可以把计算机中每一个运行的应用程序都当做是一个进程。
而一个进程又是由多个线程组成的。

static void Main(string[] args)
{
    //获得当前程序中所有正在运行的进程
    Process[] processes = Process.GetProcesses();
    foreach (var item in processes)
    {
        //关闭进程 在这不要尝试
        //item.Kill();
        Console.WriteLine(item);
    }

    //通过进程打开一些应用程序
    Process.Start("calc");
    Process.Start("mspaint");
    Process.Start("notepad");
    Process.Start("iexplore", "http://wwww.baidu.com");

    //通过进程打开指定的文件
    ProcessStartInfo psi = new ProcessStartInfo(@"D:\示例图片\0119.txt");
    //创建进程对象
    Process p = new Process();
    p.StartInfo = psi;
    p.Start();

    Console.ReadKey();
}

八、多线程

单线程给出现假死的情况

在.Net下,是不允许跨线程的访问。

在这里插入图片描述

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    Thread th;
    private void button1_Click(object sender, EventArgs e)
    {
        //单线程这样就会假死
        //创建一个线程去执行这个方法,可以随时被执行,具体什么时候执行是由CPU决定的
        th = new Thread(Test);
        //将线程设为后台线程
        th.IsBackground = true;
        th.Start();

    }
    private void Test()
    {
        for (int i = 0; i < 100000; i++)
        {
            //Console.WriteLine(i);
            //不允许跨线程的操作,但是可以取消检查
            textBox1.Text = i.ToString();
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        //取消跨线程的访问
        Control.CheckForIllegalCrossThreadCalls = false;
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        //当你点击关闭窗体的时候,判断新线程是否为null
        if (th != null) 
        {
            //结束这个线程
            //Abort以后就不能再开始了
            th.Abort();
        }
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值