简体   繁体   English

自动转义字符串中的字符

[英]Automatically escaping characters within strings

I am working on a C# project where I am exporting data from a database that is defined by the user so I have no idea what the data is going to contain or the format it is going to be in. 我正在一个C#项目中,我正在从用户定义的数据库中导出数据,所以我不知道数据将包含什么或格式将是什么。

Some of the strings within the database might include apostrophe's (') which I need to escape but everything I've found on the internet shows that I would have to do string.replace("'", "\\'"); 数据库中的某些字符串可能包含撇号('),我需要对其进行转义,但是我在互联网上找到的所有内容都表明我必须做string.replace(“'”,“ \\'”); which seems a bit odd as it would be a mass of replace statements for every possibility. 这似乎有点奇怪,因为每种可能性都有大量的替换语句。

Isn't there a better way to do this. 没有更好的方法可以做到这一点。

Thanks for any help you can provide. 感谢您的任何帮助,您可以提供。

I recently had to make a code fix for this same problem. 我最近不得不针对此问题进行代码修复。 I had to put a ton of string.replace() statements everywhere. 我不得不到处放置大量的string.replace()语句。 My recommendation would be to create a method that handles all escape character possibilities and have your query strings pass through this method before being executed. 我的建议是创建一个处理所有转义符可能性的方法,并让您的查询字符串在执行之前通过此方法。 If you design your structure correctly you should only have to call this method once. 如果正确设计结构,则只需要调用一次此方法。

    public string FixEscapeCharacterSequence(string query)
    {
        query = query.Replace("'", "\'");
        //..Any other replace statements you need
        //....

        return query;
    }

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

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