如何删除存在于某些文本中的任何UTF-8 BOM,而不是在某些文本的开头
我们收到一些文件,这些文件已被另一方联系起来。 在这些文件的中间是一些BOM
字符。
有没有办法可以检测到这3个字符并删除它们? 我已经看到很多关于如何从-start-文件中删除BOM
的例子……但不是中间的。
假设您的文件足够小以容纳在内存中,并且您有一个Enumerable.Replace
扩展方法来替换子序列,那么您可以使用:
var bytes = File.ReadAllBytes(filePath); var bom = new byte[] { 0xEF, 0xBB, 0xBF }; var empty = Enumerable.Empty(); bytes = bytes.Replace(bom, empty).ToArray(); File.WriteAllBytes(filePath, bytes);
以下是Replace
扩展方法的简单(低效)实现:
public static IEnumerable Replace ( this IEnumerable source, IEnumerable match, IEnumerable replacement) { return Replace(source, match, replacement, EqualityComparer .Default); } public static IEnumerable Replace ( this IEnumerable source, IEnumerable match, IEnumerable replacement, IEqualityComparer comparer) { int sLength = source.Count(); int mLength = match.Count(); if (sLength < mLength || mLength == 0) return source; int[] matchIndexes = ( from sIndex in Enumerable.Range(0, sLength - mLength + 1) where source.Skip(sIndex).Take(mLength).SequenceEqual(match, comparer) select sIndex ).ToArray(); var result = new List (); int sPosition = 0; foreach (int mPosition in matchIndexes) { var sPart = source.Skip(sPosition).Take(mPosition - sPosition); result.AddRange(sPart); result.AddRange(replacement); sPosition = mPosition + mLength; } var sLastPart = source.Skip(sPosition).Take(sLength - sPosition); result.AddRange(sLastPart); return result; }
- 是否存在用于防止NullReferenceException的常见模式中的竞争条件?
- 如何解决“内部.NET Framework数据提供程序错误1025”。
- 将属性添加到自定义WPF控件?
- C#如何将HttpClient Keep-Alive设置为false
- 使用包含.Net中变量名称的字符串访问方法局部变量值
- DropCreateDatabaseIfModelChanges EF6导致System.InvalidOperationException:支持上下文的模型已更改
- 如何同步等待’AuthenticationContext.AcquireTokenAsync()’?
- 使用RestSharp将POST参数添加到POST请求中
- 使用.NET RegEx在第二个’ – ‘之后检索字符串的一部分