简体   繁体   English

从文本文件中获取“字符串(路径)”时,File.Exists(Path) 总是返回 false

[英]File.Exists(Path) always return false when get 'string (Path)' from text file

I write codes to receive the path of a text file and store it in a string variable that I declare in public.我编写代码来接收文本文件的路径并将其存储在我公开声明的字符串变量中。 Then I want to know if the file exists or not by using然后我想知道文件是否存在

System.IO.File.Exists(pathoffile)

But it always returns false even though there is a file.但即使有文件,它也总是返回 false。 And then when I try to add the string path directly like this然后当我尝试像这样直接添加字符串路径时

public string propertyfile = @"C:\Users\PFA Wongsawat\Desktop\part_no_and_path_list.txt"

The function function

System.IO.File.Exists(pathoffile)

return true返回真

I already check the receive path(string) that I read from the text file.我已经检查了从文本文件中读取的接收路径(字符串)。 By cutting off "\n" and "\r" and using trim() too.But it still returns false.通过切断“\n”和“\r”并使用trim()。但它仍然返回false。 Have I missed something?我错过了什么吗? What difference between these two?.这两者有什么区别?。 I'm too new to this c#.我对这个 c# 太陌生了。 I'm very bad at this sorry in advance.我很不擅长这个对不起。

Here are my codes这是我的代码

public string pathfromread, partnumber, pathfile, portname, partnofromserial,propertypathfile; //Declare Variables
        public string propertyfile = @"C:\Users\PFA Wongsawat\Desktop\Properties.txt";
        public string pathoffile ;
        public string backuppath ;
        public string pdffolderpath  ;

private void propertyget()
        {
            if (File.Exists(propertyfile))
            {
                StreamReader readpropertyfile = new StreamReader(propertyfile);
                string readproperty;

                while ((readproperty = readpropertyfile.ReadLine()) != null)
                {
                    string[] propertyfromread = readproperty.Trim().Split('=');
                    if (propertyfromread.GetValue(0).ToString() == "pathoffile")
                    {
                        pathoffile = propertyfromread.GetValue(1).ToString();
                        pathoffile = pathoffile.Replace("\n", "").Replace("\r", "");
                        MessageBox.Show(pathoffile, "path file");
                    }
                    else if ((propertyfromread.GetValue(0).ToString() == "backuppath"))
                    {
                        backuppath = propertyfromread.GetValue(1).ToString();
                        backuppath = backuppath.Replace("\n", "").Replace("\r", "");
                        MessageBox.Show(backuppath);
                    }
                    else if ((propertyfromread.GetValue(0).ToString() == "pdffolderpath"))
                    {
                        pdffolderpath = propertyfromread.GetValue(1).ToString();
                        pdffolderpath = pdffolderpath.Replace("\n", "").Replace("\r", "");
                        MessageBox.Show(pdffolderpath);
                    }
                    else if ((propertyfromread.GetValue(0).ToString() == "portname"))
                    {
                        portname = propertyfromread.GetValue(1).ToString();
                        portname = portname.Replace("\n", "").Replace("\r", "");
                        MessageBox.Show(portname);
                    }
                }
            }

 private void Form1_Load(object sender, EventArgs e)
        {
            propertyget();

            dv = dt.DefaultView; //set dv index count to != 0 to prevent error from null input when click on remove button

            if (System.IO.File.Exists(pathoffile))//Check if file exist or not
            {

            }
            else
            {
                try
                {
                    MessageBox.Show("Database Text File Missing. Please Select New File", "Database Text File Missing", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    OpenFileDialog regispath = new OpenFileDialog();
                    regispath.Title = "Select Database Text File (part_no_and_path_list.txt)";
                    regispath.Multiselect = false;
                    regispath.Filter = "Text file (*.txt)|*.txt";
                    regispath.RestoreDirectory = true;
                    regispath.ShowDialog();
                    pathfile = regispath.FileName;
                    File.Copy(pathfile, pathoffile);
                }
                catch
                {

And this is my property text file这是我的属性文本文件

pathoffile=@"C:\Users\PFA Wongsawat\Desktop\part_no_and_path_list.txt"
backuppath=@"C:\Users\PFA Wongsawat\Documents\part_no_and_path_list.txt"
pdffolderpath=@"C:\Users\PFA Wongsawat\Downloads\"
portname=COM3

In this case the result always a messageBox showing "Database Text File Missing. Please Select New File"在这种情况下,结果总是一个消息框显示“缺少数据库文本文件。请 Select 新文件”

Thank you and sorry for my bad English.谢谢你,对不起我的英语不好。

You don't put @" and " in the text file , you only put them in the code because that's how the c# compiler knows they're strings (and knows not to interpret slashes as an escape character)您不要将@""放在文本文件中,而只是将它们放在代码中,因为 c# 编译器就是这样知道它们是字符串(并且知道不将斜杠解释为转义字符)

Just make your text file look like:只需使您的文本文件看起来像:

pathoffile=C:\Users\PFA Wongsawat\Desktop\part_no_and_path_list.txt

I also recommend you use:我还建议您使用:

Split(new []{'='}, 2)

This will allow you to use = in your path, by making split return a maximum of 2 split values;这将允许您在路径中使用 =,通过使 split 返回最多 2 个拆分值; any = that are legitimately in the path would be preserved任何合法位于路径中的 = 都将被保留

Actually I recommend you use one of the various built in settings mechanisms that c# has;实际上,我建议您使用 c# 拥有的各种内置设置机制之一; we haven't needed to read and write our own configuration files for about 25 years大约 25 年我们不需要读写自己的配置文件

If you really do want to continue rolling your own you can reduce your code massively by using a dictionary如果你真的想继续自己滚动,你可以通过使用字典来大量减少你的代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

public class Settings{
    private Dictionary<string,string> _conf = new Dictionary<string,string>();

    public string PathOfFile {
      get => _conf["pathoffile"];
    }

    public void ReadConfig(){
      File.ReadAllLines("conf.txt").ToDictionary(
        x => x.Split(new[]{'='},2)[0],
        x => x.Split(new[]{'='},2)[1]
      );
    }
}

Yep, it's all you need.是的,这就是你所需要的。 Every time you want to add another setting, add another property (like public string PathOfFile), add another love to the file and make sure the string in the property matches the line in the file每次你想添加另一个设置时,添加另一个属性(如公共字符串 PathOfFile),向文件添加另一个爱,并确保属性中的字符串与文件中的行匹配

In other areas, please read up on c# naming conventions;在其他领域,请阅读 c# 命名约定; PublicThingsAreNamedLikeThis, _privateLikeThis, localLikeThis, neverlikethis PublicThingsAreNamedLikeThis, _privateLikeThis, localLikeThis, neverlikethis

Thank you I've already solved this problem谢谢 我已经解决了这个问题

By remove "@" and '""' from path in the property text file like this.通过像这样从属性文本文件中的路径中删除“@”和“”“”。

pathoffile=C:\Users\PFA Wongsawat\Desktop\part_no_and_path_list.txt
backuppath=C:\Users\PFA Wongsawat\Documents\part_no_and_path_list.txt
pdffolderpath=C:\Users\PFA Wongsawat\Downloads\
portname=COM3

The reason I can't see this because I debug the program by seeing the result in message box and it not match with the real one.我看不到这一点的原因是我通过在消息框中查看结果来调试程序并且它与真实的不匹配。 Thank you.谢谢你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM