“不支持给定路径的格式。”

发布于 2024-12-03 17:12:39 字数 497 浏览 3 评论 0原文

我的 Web 服务中有以下代码:

string str_uploadpath = Server.MapPath("/UploadBucket/Raw/");
FileStream objfilestream = new FileStream(str_uploadpath +
                fileName, FileMode.Create, FileAccess.ReadWrite);

有人可以帮我解决代码第 2 行中的此错误消息的问题吗?

不支持给定路径的格式。

该文件夹的权限设置为所有人的完全访问权限,这是该文件夹的实际路径。

该断点为我提供了 str_uploadpath 的值为 C:\\webprojects\\webservices\\UploadBucket\\Raw\\

这个字符串有什么问题吗?

I have the following code in my web service:

string str_uploadpath = Server.MapPath("/UploadBucket/Raw/");
FileStream objfilestream = new FileStream(str_uploadpath +
                fileName, FileMode.Create, FileAccess.ReadWrite);

Can someone help me resolve the issue with this error message from line 2 of the code.

The given path's format is not supported.

Permission on the folder is set to full access to everyone and it is the actual path to the folder.

The breakpoint gave me the value of str_uploadpath as C:\\webprojects\\webservices\\UploadBucket\\Raw\\.

What is wrong with this string?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

遗弃M 2024-12-10 17:12:39

不要使用 str_uploadpath + fileName,而是尝试使用 System.IO.Path .Combine 代替:

Path.Combine(str_uploadpath, fileName);

返回一个字符串。

Rather than using str_uploadpath + fileName, try using System.IO.Path.Combine instead:

Path.Combine(str_uploadpath, fileName);

which returns a string.

东风软 2024-12-10 17:12:39

我看到发起者发现尝试使用完整路径保存文件名时发生了错误。实际上,文件名中包含 ":" 就足以引发此错误。如果您的文件名中可能包含 ":" (例如,如果您的文件名中包含日期戳),请确保将其替换为其他内容。 IE:

string fullFileName = fileName.Split('.')[0] + "(" + DateTime.Now.ToString().Replace(':', '-') + ")." + fileName.Split('.')[1];

I see that the originator found out that the error occurred when trying to save the filename with an entire path. Actually it's enough to have a ":" in the file name to get this error. If there might be ":" in your file name (for instance if you have a date stamp in your file name) make sure you replace these with something else. I.e:

string fullFileName = fileName.Split('.')[0] + "(" + DateTime.Now.ToString().Replace(':', '-') + ")." + fileName.Split('.')[1];
你的呼吸 2024-12-10 17:12:39

对我来说,这个问题是人眼看不见的 "" Left-To-右嵌入字符。
在我从 Windows 文件属性安全选项卡复制粘贴路径后,它卡在字符串的开头(就在“D”之前)。

var yourJson = System.IO.File.ReadAllText(@"D:\test\json.txt"); // Works
var yourJson = System.IO.File.ReadAllText(@"‪D:\test\json.txt"); // Error

因此,乍一看相同的两条线实际上是不同的。

For me the problem was an invisible to human eye "‪" Left-To-Right Embedding character.
It stuck at the beginning of the string (just before the 'D'), after I copy-pasted the path, from the windows file properties security tab.

var yourJson = System.IO.File.ReadAllText(@"D:\test\json.txt"); // Works
var yourJson = System.IO.File.ReadAllText(@"‪D:\test\json.txt"); // Error

So those, identical at first glance, two lines are actually different.

維他命╮ 2024-12-10 17:12:39

如果您尝试将文件保存到文件系统。 Path.Combine 不是防弹的,因为如果文件名包含无效字符,它不会为您提供帮助。这是一个从文件名中删除无效字符的扩展方法:

public static string ToSafeFileName(this string s)
{
        return s
            .Replace("\\", "")
            .Replace("/", "")
            .Replace("\"", "")
            .Replace("*", "")
            .Replace(":", "")
            .Replace("?", "")
            .Replace("<", "")
            .Replace(">", "")
            .Replace("|", "");
    }

用法可以是:

Path.Combine(str_uploadpath, fileName.ToSafeFileName());

If you are trying to save a file to the file system. Path.Combine is not bullet proof as it won't help you if the file name contains invalid characters. Here is an extension method that strips out invalid characters from file names:

public static string ToSafeFileName(this string s)
{
        return s
            .Replace("\\", "")
            .Replace("/", "")
            .Replace("\"", "")
            .Replace("*", "")
            .Replace(":", "")
            .Replace("?", "")
            .Replace("<", "")
            .Replace(">", "")
            .Replace("|", "");
    }

And the usage can be:

Path.Combine(str_uploadpath, fileName.ToSafeFileName());
一念一轮回 2024-12-10 17:12:39

可能导致此错误的其他原因包括:

完整的 PathFile 字符串中不能包含某些字符。

例如,这些字符将使 StreamWriter 函数崩溃:

"/"  
":"

可能还有其他特殊字符也会使其崩溃。
例如,当您尝试将 DateTime 标记放入文件名中时,我发现会发生这种情况:

AppPath = Path.GetDirectoryName(giFileNames(0))  
' AppPath is a valid path from system. (This was easy in VB6, just AppPath = App.Path & "\")
' AppPath must have "\" char at the end...

DateTime = DateAndTime.Now.ToString ' fails StreamWriter... has ":" characters
FileOut = "Data_Summary_" & DateTime & ".dat"
NewFileOutS = Path.Combine(AppPath, FileOut)
Using sw As StreamWriter = New StreamWriter(NewFileOutS  , True) ' true to append
        sw.WriteLine(NewFileOutS)
        sw.Dispose()
    End Using

防止此问题的一种方法是将 NewFileOutS 中的问题字符替换为良性字符:

' clean the File output file string NewFileOutS so StreamWriter will work
 NewFileOutS = NewFileOutS.Replace("/","-") ' replace / with -
 NewFileOutS = NewFileOutS.Replace(":","-") ' replace : with - 

' after cleaning the FileNamePath string NewFileOutS, StreamWriter will not throw an (Unhandled) exception.

希望这可以为某人节省一些麻烦...!

Among other things that can cause this error:

You cannot have certain characters in the full PathFile string.

For example, these characters will crash the StreamWriter function:

"/"  
":"

there may be other special characters that crash it too.
I found this happens when you try, for example, to put a DateTime stamp into a filename:

AppPath = Path.GetDirectoryName(giFileNames(0))  
' AppPath is a valid path from system. (This was easy in VB6, just AppPath = App.Path & "\")
' AppPath must have "\" char at the end...

DateTime = DateAndTime.Now.ToString ' fails StreamWriter... has ":" characters
FileOut = "Data_Summary_" & DateTime & ".dat"
NewFileOutS = Path.Combine(AppPath, FileOut)
Using sw As StreamWriter = New StreamWriter(NewFileOutS  , True) ' true to append
        sw.WriteLine(NewFileOutS)
        sw.Dispose()
    End Using

One way to prevent this trouble is to replace problem characters in NewFileOutS with benign ones:

' clean the File output file string NewFileOutS so StreamWriter will work
 NewFileOutS = NewFileOutS.Replace("/","-") ' replace / with -
 NewFileOutS = NewFileOutS.Replace(":","-") ' replace : with - 

' after cleaning the FileNamePath string NewFileOutS, StreamWriter will not throw an (Unhandled) exception.

Hope this saves someone some headaches...!

习惯成性 2024-12-10 17:12:39

如果您在 PowerShell 中收到此错误,很可能是因为您使用 Resolve-Path 来解析远程路径,例如

 Resolve-Path \\server\share\path

在本例中,Resolve-Path 返回一个对象当转换为字符串时,不会返回有效的路径。它返回 PowerShell 的内部路径:

> [string](Resolve-Path \\server\share\path)
Microsoft.PowerShell.Core\FileSystem::\\server\share\path

解决方案是在 Resolve-Path 返回的对象上使用 ProviderPath 属性:

> Resolve-Path \\server\share\path | Select-Object -ExpandProperty PRoviderPath
\\server\share\path
> (Resolve-Path \\server\share\path).ProviderPath
\\server\share\path

If you get this error in PowerShell, it's most likely because you're using Resolve-Path to resolve a remote path, e.g.

 Resolve-Path \\server\share\path

In this case, Resolve-Path returns an object that, when converted to a string, doesn't return a valid path. It returns PowerShell's internal path:

> [string](Resolve-Path \\server\share\path)
Microsoft.PowerShell.Core\FileSystem::\\server\share\path

The solution is to use the ProviderPath property on the object returned by Resolve-Path:

> Resolve-Path \\server\share\path | Select-Object -ExpandProperty PRoviderPath
\\server\share\path
> (Resolve-Path \\server\share\path).ProviderPath
\\server\share\path
嘴硬脾气大 2024-12-10 17:12:39

尝试将

Server.MapPath("/UploadBucket/Raw/")

更改为

Server.MapPath(@"\UploadBucket\Raw\")

Try changing:

Server.MapPath("/UploadBucket/Raw/")

to

Server.MapPath(@"\UploadBucket\Raw\")

韬韬不绝 2024-12-10 17:12:39

这是我的问题,可能对其他人有帮助——尽管这不是OP的问题:

DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.ToString());

我通过将路径输出到日志文件来确定问题,并发现它的格式不正确。对我来说正确的很简单:

DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.FullName.ToString());

This was my problem, which may help someone else -- although it wasn't the OP's issue:

DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.ToString());

I determined the problem by outputting my path to a log file, and finding it not formatting correctly. Correct for me was quite simply:

DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.FullName.ToString());
空城之時有危險 2024-12-10 17:12:39

使用 Path.Combine 方法有帮助吗?这是将文件路径连接在一起的更安全的方法。可能是在将路径连接在一起时遇到问题

Does using the Path.Combine method help? It's a safer way for joining file paths together. It could be that it's having problems joining the paths together

美人如玉 2024-12-10 17:12:39

我今天也遇到了同样的问题。
我尝试加载到代码中的文件已打开以在 Excel 中进行编辑。
关闭Excel后,代码开始工作!

I had the same issue today.
The file I was trying to load into my code was open for editing in Excel.
After closing Excel, the code began to work!

↙温凉少女 2024-12-10 17:12:39

我正在使用变量的(有限)表达式构建器在简单的文件系统任务中使用,以在 SSIS 中对文件进行存档。

这是我快速而肮脏的技巧,用于删除冒号以阻止错误:
@[用户::LocalFile] + "-" + REPLACE((DT_STR, 30, 1252) GETDATE(), ":", "-") + ".xml"

I am using the (limited) Expression builder for a Variable for use in a simple File System Task to make an archive of a file in SSIS.

This is my quick and dirty hack to remove the colons to stop the error:
@[User::LocalFile] + "-" + REPLACE((DT_STR, 30, 1252) GETDATE(), ":", "-") + ".xml"

离不开的别离 2024-12-10 17:12:39
Image img = Image.FromFile(System.IO.Path.GetFullPath("C:\\ File Address"));

您需要通过指向类获取完整路径。我有同样的错误并修复了...

Image img = Image.FromFile(System.IO.Path.GetFullPath("C:\\ File Address"));

you need getfullpath by pointed class. I had same error and fixed...

此生挚爱伱 2024-12-10 17:12:39

如果值是像 file://C:/whatever 这样的文件 url,请使用 Uri 类转换为常规文件名:

var localPath = (new Uri(urlStylePath)).AbsolutePath

一般来说,使用提供的 API 是最佳实践。

If the value is a file url like file://C:/whatever, use the Uri class to translate to a regular filename:

var localPath = (new Uri(urlStylePath)).AbsolutePath

In general, using the provided API is best practice.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文