[英]Writing a string to a file causes an exception in C#
我收到一个我不明白的“ FormatException:输入字符串格式不正确”的错误。
我使用以下几行将字符串写入文本文件:
using (StreamWriter sw = new StreamWriter(myfilename, false, System.Text.Encoding.GetEncoding(enc)))
{
sw.Write(mystring, Environment.NewLine);
}
(编码部分是因为我在应用程序中确实有一个选项可以将其设置为utf-8或iso-8859-1 ...,但是我认为这是无关紧要的)。
我的所有字符串都写得很好,除了这一个字符串与其他字符串不同以外,因为它实际上包含了一段JavaScript代码。 我确定那里的特殊字符之一可能是导致问题的原因,但我怎么知道?
我尝试做的一件事是在上述sw.Write语句之前插入以下行:
System.Console.WriteLine(mystring);
它写到控制台就好了-没有错误。
救命?
谢谢! (新年快乐!)
-阿德娜
您正在使用的重载将格式作为第一个参数,然后再注入对象。
您可以执行以下任一操作:
sw.Write(mystring + Environment.NewLine);
要么
sw.Write("{0}{1}", mystring, Environment.NewLine);
为了回应DK的评论,我测试了扩展字符串串联的速度较慢。 我通过三个选项进行了设置:
sw.Write
sw.WriteLine
在我的机器上,第二个选项比平均速度快88%。 在10000000次迭代中,它们使用3517、2420和3385毫秒。
仅当这是程序中多次调用的代码时,才有意义。
using System;
using System.IO;
using System.Text;
class Program
{
static void Main(string[] args)
{
const string myString = "kdhlkhldhcøehdhkjehdkhekdhk";
int iterations=getIntFromParams(args, 0, 10);
int method = getIntFromParams(args, 1, 0);
var fileName=Path.GetTempFileName();
using (StreamWriter sw = new StreamWriter(fileName, false, Encoding.Default))
{
switch (method)
{
case 0:
Console.WriteLine("Starting method with concatenation. Iterations: " + iterations);
var start0 = DateTimeOffset.Now;
for (int i = 0; i < iterations; i++)
{
sw.Write(myString + Environment.NewLine);
}
var time0 = DateTimeOffset.Now - start0;
Console.WriteLine("End at " + time0.TotalMilliseconds + " ms.");
break;
case 1:
Console.WriteLine("Starting method without concatenation. Iterations: " + iterations);
var start1 = DateTimeOffset.Now;
for (int i = 0; i < iterations; i++)
{
sw.Write(myString);
sw.Write(Environment.NewLine);
}
var time1 = DateTimeOffset.Now - start1;
Console.WriteLine("End at " + time1.TotalMilliseconds + " ms.");
break;
case 2:
Console.WriteLine("Starting method without concatenation, using WriteLine. Iterations: " + iterations);
var start2 = DateTimeOffset.Now;
for (int i = 0; i < iterations; i++)
{
sw.WriteLine(myString);
}
var time2 = DateTimeOffset.Now - start2;
Console.WriteLine("End at " + time2.TotalMilliseconds + " ms.");
break;
}
}
}
private static int getIntFromParams(string[] args, int index, int @default)
{
int value;
try
{
if (!int.TryParse(args[index], out value))
{
value = @default;
}
}
catch(IndexOutOfRangeException)
{
value = @default;
}
return value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.