从文本文件到C#中的文本框读取随机行 [英] Read random line from text file to text box in C#

查看:48
本文介绍了从文本文件到C#中的文本框读取随机行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究此程序,它的功能之一是具有一个部分,该程序会自动从文本文件中随机选择一行(其中所包含的内容并不重要),并将其显示在文本框中.

I am working on this program, and one of its features is to have a section where the program automatically randomly selects a line from a text file (what it contains is not important) and display this in a text box.

我花了很多时间来混合和匹配各种代码(streamReader等),但是似乎没有什么可以尝试的.

I have spend lots of time mixing and matching various code (streamReader etc.) but nothing I seem to try works.

这个我知道的作品大声笑:Random rand = new Random();

this I know works lol: Random rand = new Random();

另外,请请不要仅仅给我一些网站的链接来帮助我,因为那些网站对我来说很混乱.

Also, please please PLEASE, do not just give me the link of some website to help me, because those websites are very confusing to me.

我要问的是有人向我解释我应该做什么以及我应该拥有什么代码.

All I'm asking is that someone explain to me what I should be doing and what code i should have.

谢谢您!

推荐答案

这将从文件中返回随机行:

This will return a random line from a file:

private static Random _rand = new Random();    

public static string GetRandomLine(string filename)
{
    var lines = File.ReadAllLines(filename);

    var lineNumber = _rand.Next(0, lines.Length);

    return lines[lineNumber];
}

这篇关于从文本文件到C#中的文本框读取随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆