我想检查字符串以确保它不包含任何控制字符。我想出了这个解决方案。您是否同意它足以达到预期目的?我有什么明显错过的吗?
string input = "2cancer'.pdf";
char[] chars = input.ToCharArray();
foreach (var c in chars)
{
if(c == 127 || (c < ' ' && c != '\t'))
{
throw new Exception("Control character detected");
}
}
这背景是将文件上传到RavenDB的问题,它抱怨文件名包含一个无效的控制字符',所以我希望检测到无效的控制字符并删除它或抛出异常提醒用户,虽然我可能会做前者。
异常的堆栈跟踪是:
[ArgumentException: Specified value has invalid Control characters.
Parameter name: value]
System.Net.WebHeaderCollection.CheckBadChars(String name, Boolean isHeaderValue) +8426470
System.Net.WebHeaderCollection.Set(String name, String value) +86
Raven.Client.Connection.HttpJsonRequest.WriteMetadata(RavenJObject metadata) in c:\Builds\RavenDB-Stable\Raven.Client.Lightweight\Connection\HttpJsonRequest.cs:573
Raven.Client.Connection.HttpJsonRequest..ctor(CreateHttpJsonRequestParams requestParams, HttpJsonRequestFactory factory) in c:\Builds\RavenDB-Stable\Raven.Client.Lightweight\Connection\HttpJsonRequest.cs:91
Raven.Client.Connection.HttpJsonRequestFactory.CreateHttpJsonRequest(CreateHttpJsonRequestParams createHttpJsonRequestParams) in c:\Builds\RavenDB-Stable\Raven.Client.Lightweight\Connection\HttpJsonRequestFactory.cs:57
Raven.Client.Connection.ServerClient.DirectPutAttachment(String key, RavenJObject metadata, Nullable`1 etag, Stream data, String operationUrl) in c:\Builds\RavenDB-Stable\Raven.Client.Lightweight\Connection\ServerClient.cs:490
Raven.Client.Connection.<>c__DisplayClass19.<PutAttachment>b__18(String operationUrl) in c:\Builds\RavenDB-Stable\Raven.Client.Lightweight\Connection\ServerClient.cs:441
Raven.Client.Connection.<>c__DisplayClassa.<ExecuteWithReplication>b__9(String operationUrl) in c:\Builds\RavenDB-Stable\Raven.Client.Lightweight\Connection\ServerClient.cs:167
Raven.Client.Connection.ReplicationInformer.TryOperation(Func`2 operation, String operationUrl, Boolean avoidThrowing, T& result) in c:\Builds\RavenDB-Stable\Raven.Client.Lightweight\Connection\ReplicationInformer.cs:564
Raven.Client.Connection.ReplicationInformer.ExecuteWithReplication(String method, String primaryUrl, Int32 currentRequest, Int32 currentReadStripingBase, Func`2 operation) in c:\Builds\RavenDB-Stable\Raven.Client.Lightweight\Connection\ReplicationInformer.cs:523
Raven.Client.Connection.ServerClient.ExecuteWithReplication(String method, Func`2 operation) in c:\Builds\RavenDB-Stable\Raven.Client.Lightweight\Connection\ServerClient.cs:174
我知道这是我使用的RavenDB版本中的一个错误,但是目前我无法升级数据库。
答案 0 :(得分:3)
使用Char.IsControl
检查角色是否为控制角色。
答案 1 :(得分:2)
string input = "2cancer'.pdf";
char[] chars = input.ToCharArray();
foreach (var c in chars)
{
if (char.IsPunctuation(c) || char.IsSymbol(c) || char.IsControl(c))
{
throw new Exception("Control character detected");
}
}