3

我需要一个通过查找文件创建的 url,可以获取该文件的 url,我得到了这个:

"C:\\dev\\vsprojects\\MvcApplication4\\MvcApplication4\\hard.txt"

一切都运行良好,当我更换\\by时问题就来了,\但它不起作用!这是代码:

string ruta = "";

foreach (var readText in
    Directory.GetFiles(@"C:\dev\vsprojects\MvcApplication4\MvcApplication4",
    "stringCon.txt", SearchOption.AllDirectories))
{
    ruta = readText;
}

ruta = ruta.Replace(@"\\", @"\");
//in debugger mode says ruta parameter still having
//the \\ and i cant get the content of the txt file
TextReader ReadTXT_file = new StreamReader(ruta);
//and here says that StringConexion is null, why??
string StringConexion = ReadTXT_file.ReadLine();

ReadTXT_file.Close();
4

1 回答 1

3

好吧,不完全确定您要做什么,但是,您的“替换”代码在循环之外你需要它,否则你只会替换最后一个文件的文本。

public class e{


        string ruta = "";

                foreach(var readText in Directory.GetFiles(@"C:\dev\vsprojects\MvcApplication4\MvcApplication4", "stringCon.txt", SearchOption.AllDirectories)) {

                    ruta = readText;
                    ruta = ruta.Replace(@"\\", @"\");
    //in debugger mode says ruta parameter still having the \\ and i cant get the content of the txt file
                TextReader ReadTXT_file = new StreamReader(ruta);
    //and here says that StringConexion is null, why??
                string StringConexion = ReadTXT_file.ReadLine();//

                ReadTXT_file.Close(); 

                }



}

编辑

刚刚意识到这甚至不会编译。而你的班级被称为“e”。我对这一切有点害怕,但我还是建议用这种格式来创建类/方法......

public class MyProperClassName
{
    public void MyMethodName()
    {
        // do your file text operations here
    }
}
于 2013-03-21T15:27:08.687 回答