[英]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.