问题描述
我在电子中打开一个对话框来选择一个文件夹,我想读出文件路径。 但是 result.filePaths 给了我一个带有 \\ 的文件路径,这对我来说是不可行的,以便稍后阅读文件夹中的文件。 ?
现在的结果:
“P:\\社交媒体\\音板\\声音”
预期结果:
“P:/社交媒体/音板/声音”
有没有办法把它转换成“/”? ?
我的代码:
const dialog = require('electron').remote.dialog
dialog.showOpenDialog({
properties: ['openDirectory','multiSelections']
}).then(result => {
//Get Selected Folders
folderpath = result.filePaths
console.log(folderpath)
});
解决方法
Windows 使用 \
而不是 /
来分隔嵌套资源。但它支持两者。如果您仍想将 \\
转换为 /
。你可以试试下面的方法。
//Get Selected Folders
folderpath = result.filePaths.replaceAll('\\','/');
console.log(folderpath);
,
以下是我开发电子应用程序以在 unix 和 windows 上运行而没有任何问题的方法。
我没有使用 path
模块函数,而是通过使用下面的模块来扩展功能并调用它。这将清理所有路径并将它们转换为正确的 unix 路径,如“/var/path/file”或“C:/path/file”。
Windows 实际上可以使用 unix 路径来创建/读取/更新/移动文件和文件夹。
export default {
extname (file) {
return path.extname(file)
},resolve () {
return this.sanitizePath(Array.from(arguments).join('/').replace('//','/'))
},normalize () {
const file = this.resolve(...arguments)
return this.sanitizePath(path.normalize(file))
},basename (file,ext = '') {
return this.sanitizePath(path.basename(file,ext))
},dirname (file) {
return this.sanitizePath(path.dirname(file))
},relative (from,to) {
return this.sanitizePath(path.relative(path.resolve(from),path.resolve(to)))
},sanitizePath (absPath) {
// fix windows separator
return absPath.replaceAll(path.sep,'/')
}
}
我唯一需要使用 Windows 特定路径的时候是使用 shell.moveItemToTrash(file)
,为此我必须使用这个客户端函数
convertPathForWin (file,os = navigator.platform) {
return (os.toLowerCase() === 'win32') ? file.replaceAll('/','\\') : file
}