【问题标题】:Replace method not working c#? Whats wrong here替换方法不起作用c#?这里有什么问题
【发布时间】:2013-09-06 00:08:41
【问题描述】:

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

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

一切正常,当我将\\ 替换为\ 时,问题就来了,但它不起作用!代码如下:

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();

【问题讨论】:

  • 我不明白您为什么要尝试替换双反斜杠,因为它不应该出现在您的字符串中。我也不明白你想用foreach 完成什么。在调试器模式下,它将反斜杠显示为正确转义的反斜杠。而StringConexion 在给定点是null,因为您在下一行为它分配了一个值,那么您希望它具有什么值。
  • 感谢@mgttlinger,我做到了,你在哪里正确
  • @user2195741 我不知道我建议做什么,但我很高兴能提供帮助

标签: c# asp.net-mvc-3


【解决方案1】:

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

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
    }
}

【讨论】:

    猜你喜欢
    • 2012-11-21
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多