简体   繁体   English

正则表达式替换过载?

[英]Regex.Replace overload?

so I have the following code which generates a sha256 hash of the file data of the file that was uploaded by the user. 所以我有以下代码,该代码生成用户上传的文件的文件数据的sha256哈希。 This works fine but sometimes it includes illegal characters (for the windows os). 这可以正常工作,但有时它包含非法字符(对于Windows操作系统)。

So what I'm trying to implement is a try catch to strip of illegal characters. 因此,我要尝试实现的尝试是去除非法字符。 I have pulled this information off of Microsoft's website itself. 我已经从Microsoft网站本身获取了此信息。 However, when implemented with Regex.Replace() I'm told that it only accepts 5 overloads. 但是,当使用Regex.Replace()实现时,会告诉我它仅接受5个重载。

Which is confusing because that is what I have and I have triple checked that my hashedfile1name is a string type variable. 这是令人困惑的,因为那是我所拥有的,我已经hashedfile1name检查了我的hashedfile1name是字符串类型变量。

The other problem is that for the try catch its telling me that it doesn't know what RegexMatchTimeoutException is. 另一个问题是尝试捕获它告诉我它不知道什么是RegexMatchTimeoutException But there are no more imports/using statements in Microsoft's example . 但是在Microsoft的示例中,没有更多的import / using语句。

try
{
    FileUpload1.SaveAs("C:\\direct\\uploads\\" + FileUpload1.FileName);
    using (fs = File.OpenRead("C:\\direct\\uploads\\" + FileUpload1.FileName))
    {
        byte[] bytes = new byte[fs.Length];
        fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
        hashedfile1name = Convert.ToBase64String(hash.ComputeHash(bytes));
    }
    try
    {
        Regex.Replace(hashedfile1name, @"[^\w\.@-]", "", RegexOptions.None, TimeSpan.FromSeconds(1.5));
    }
    catch (RegexMatchTimeoutException)
    {
        hashedfile1name = "";
    }
    FileUpload1.SaveAs("C:\\direct\\uploads\\" + hashedfile1name);
    File.Delete("C:\\direct\\uploads\\" + FileUpload1.FileName);

    Label1.Text = "File name: " + FileUpload1.PostedFile.FileName + " - " + hashedfile1name;
}
catch (Exception ex)
{
    Label1.Text = "ERROR: " + ex.Message.ToString();
}

Regex.Replace does not replace in-place; Regex.Replace不能就地替换; it returns the replacement as a string. 它以字符串形式返回替换项。 The segment: 细分:

try
{
    Regex.Replace(hashedfile1name, @"[^\w\.@-]", "", RegexOptions.None, TimeSpan.FromSeconds(1.5));
}
catch (RegexMatchTimeoutException)
{
    hashedfile1name = "";
}

Can be replaced with simply: 可以简单地替换为:

hashedfile1name = Regex.Replace(hashedfile1name, @"[^\w\.@-]", "");

Your code should then function as expected. 然后,您的代码应该可以按预期运行。

(If you want to preserve the entire hash, you might want to consider Base-32 encoding, which is similar to base64 but uses only alphanumeric characters. .NET does not include a Base32 methods, but an implementation is provided in Shane's answer here .) (如果要保留整个哈希,则可能需要考虑Base-32编码,该编码与base64相似,但仅使用字母数字字符。.NET不包括Base32方法,但是Shane的答案此处提供了一种实现。 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM