随机读取某一个txt文本文档的内容

1.   System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
     获取模块的完整路径,包括文件名。
2.   System.Environment.CurrentDirectory
     获取和设置当前目录(该进程从中启动的目录)的完全限定目录。
3.   System.IO.Directory.GetCurrentDirectory()
     获取应用程序的当前工作目录。这个不一定是程序从中启动的目录啊,有可能程序放在C:\www里,这个函数有可能返回C:\Documents and Settings\ZYB\,或者C:\Program Files\Adobe\,有时不一定返回什么东东,这是任何应用程序最后一次操作过的目录,比如你用Word打开了E:\doc\my.doc这个文件,此时执行这个方法就返回了E:\doc了。
4. System.AppDomain.CurrentDomain.BaseDirectory
     获取程序的基目录。
5. System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase
     获取和设置包括该应用程序的目录的名称。
6. System.Windows.Forms.Application.StartupPath
     获取启动了应用程序的可执行文件的路径。效果和2、5一样。只是5返回的字符串后面多了一个"\"而已
7. System.Windows.Forms.Application.ExecutablePath
     获取启动了应用程序的可执行文件的路径及文件名,效果和1一样。

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtData();
        }
    }

    /// <summary>
    /// 随机获取TXT文件名
    /// </summary>
    private string RandomTxtName()
    {

        string txtName = "";  //文件名
        int random = 0;  //随机数
        int randomCount = 0;   //随机数总数
      string txtStr = System.AppDomain.CurrentDomain.BaseDirectory; //  获取当前相对路径
      txtStr += "\\hanbag";
      //获取指定目录下的所有文件夹名  
      ArrayList a = new ArrayList();
      DirectoryInfo d = new DirectoryInfo(txtStr);
      FileInfo[] fis = d.GetFiles();
      foreach (FileInfo fi in fis)
      {
          a.Add(fi.Name);
          txtName += fi.Name;
          randomCount += 1;

      }
      txtName=txtName.Replace(".txt", ",");
      txtName = txtName.Substring(0, txtName.Length - 1);
      Random rd = new Random();
      random = rd.Next(randomCount);
      string[] s = txtName.Split(new char[1] {','});

      txtName =txtStr+"\\"+ s[random].ToString()+".txt"; //随机获取的文件名
      return txtName;

    }




    //读取txt内容
    private void txtData()
    {
        string file = RandomTxtName();
        string[] strings = File.ReadAllLines(file);
        List<string> countries = new List<string>();
        countries.AddRange(strings);
        countries.Sort();
        foreach (string s in countries)
        {
            Response.Write(s+"<br \\>");
        }
    }

}

 

posted @ 2013-03-15 12:19  乡土的味道  阅读(825)  评论(0编辑  收藏  举报