You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用InputField输入ID时File.Exists始终返回false,硬编码ID则正常

问题解决:InputField获取ID拼接路径后File.Exists返回false的排查方案

核心问题

用户输入ID拼接路径后,File.Exists()始终返回false,但硬编码相同ID却能正常识别,控制台打印路径字符串看似一致。

可能原因及解决方法

1. 输入含隐藏空白字符

InputField的输入可能包含空格、制表符、换行符等肉眼不可见的字符,导致路径实际不匹配。
解决代码:

// 清理输入:去除首尾空白,过滤换行/制表符
string cleanInput = UserInput.text.Trim().Replace("\t", "").Replace("\n", "").Replace("\r", "");
// 或用正则保留合法ID字符(示例:仅保留十六进制字符)
// string cleanInput = Regex.Replace(UserInput.text, @"[^0-9A-Fa-f]", "");
string pathInput = Path.Combine(BackupBO.Instance.DirectoryName, BackupSelected, cleanInput + ".txt");

2. 字符串字节不一致(肉眼不可见差异)

即使控制台显示相同,字符串的字节序列可能存在差异(如编码问题、全角/半角字符)。
验证代码:

byte[] pathBytes = Encoding.UTF8.GetBytes(path);
byte[] pathInputBytes = Encoding.UTF8.GetBytes(pathInput);

Debug.Log("硬编码路径字节: " + BitConverter.ToString(pathBytes));
Debug.Log("输入路径字节: " + BitConverter.ToString(pathInputBytes));

对比字节序列即可直接定位差异。

3. 路径拼接错误

手动拼接/可能在不同平台出现兼容性问题,改用Path.Combine自动处理路径分隔符:
优化代码:

// 硬编码路径
string path = Path.Combine(BackupBO.Instance.DirectoryName, BackupSelected, "BBC24F4DE88E4031.txt");
// 输入拼接路径
string pathInput = Path.Combine(BackupBO.Instance.DirectoryName, BackupSelected, UserInput.text.Trim() + ".txt");

原问题代码

string path = BackupBO.Instance.DirectoryName + BackupSelected + "/" + "BBC24F4DE88E4031.txt";//UserInput en teoria
string pathInput = BackupBO.Instance.DirectoryName + BackupSelected + "/" + UserInput.text+".txt";
Debug.Log("Path with string literal: "+path);
Debug.Log("Path with UserInput: " + pathInput);
Debug.Log("Does the path with string literal exist?" + File.Exists(path));
Debug.Log("Does the path with UserInput exist?" + File.Exists(pathInput));

内容的提问来源于stack exchange,提问作者Javi Gauxachs Monserrat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 12:23:03