防止在 .NET 上构建路径中的反斜杠以进行跨平台部署
我有一个遗留的 .NET 应用程序,我已将其移植到 .NET 6.0 并正在执行跨平台(Windows 和 Linux)。
许多遗留代码是通过硬编码路径创建来开发的,在字符串中使用反斜杠,就像
new StreamWriter(FeuxBarreFolderName + @"\\JazzSchmazz.txt");
我已经转换为类似
new StreamWriter(Path.Combine(FeuxBarreFolderName, "JazzSchmazz.txt"));
我想防止任何开发人员意外或故意在硬编码路径中再次添加 \ 的内容。除了在代码审查时处理此问题之外,是否有一种方法可以通过代码分析或测试时的严重失败自动执行此操作?我的搜索没有帮助。
我的想法是
- 修改 Docker 集成测试中的 ext4 文件系统,以防止文件名带有 \.我不知道这是否可能/合理。
- 在我的 Docker 集成测试中发挥创意,防止在根目录中创建文件(从父目录中删除 w),但允许在子目录中创建文件(添加 w > 再次到特定的子目录)。这感觉超级脆。
- 查找或编写一个分析器来查看字符串并抱怨任何包含 \ 字符的字符串。
这里有更好的方法吗?
I have a legacy .NET application that I have ported to .NET 6.0 and am executing cross platform (Windows & Linux).
Much of the legacy code was developed with hard coded path creation, using backslash in strings, like
new StreamWriter(FeuxBarreFolderName + @"\\JazzSchmazz.txt");
that I have converted to something like
new StreamWriter(Path.Combine(FeuxBarreFolderName, "JazzSchmazz.txt"));
I want to prevent any developer from accidentally or purposefully adding \ in a hard coded path again. Other than handling this at code review, is there a way that I can do this automatically, either by code analysis or spectacular failure at testing time? My searches have been unhelpful.
Ideas that I've had
- Modify the ext4 filesystem on my Docker integration tests to prevent filenames with a \. I have no idea if this is possible / reasonable.
- Get creative with permissions on my Docker integration tests to prevent creating files in a root directory (take away w from the parent dir), but allow it on the child dir (add w again to a specific child dir). This feels super brittle.
- Find or write an analyzer to look at strings and complain about any strings that contain a \ character.
Is there a better way here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于没有内置方法可以在开发或执行时防止出现这种情况,因此我将添加此代码以在集成测试后运行。如果发现任何使用不适当的字符(反斜杠)创建的文件或目录,它将扫描文件系统并抛出异常。
我还想添加对冒号的检查,以防人们创建类似“c:\feux\barre.txt”的路径,但看起来至少 NuGet 使用冒号创建目录(例如
~/.local/share/NuGet/v3-cache/670c1461c29885f9aa22c281d8b7da90845b38e4$ps:_api.nuget.org_v3_index.json
)As there's not a built in way to protect against this at development or execution time, I'm going to add this code to run after my integration tests. It will sweep the filesystem and throw an exception if it finds any files or directories created with an inappropriate character (backslash).
I wanted to add a check for colon as well, in case folks were creating paths like "c:\feux\barre.txt", but it looks like at least NuGet creates directories with colon (ex.
~/.local/share/NuGet/v3-cache/670c1461c29885f9aa22c281d8b7da90845b38e4$ps:_api.nuget.org_v3_index.json
)