我目前正在解析生產報告的項目。生產報告上傳到我們的網站,然後請求解析它們。這些文件放置在我們可以參考的SqlServer數據庫中,以將文件拖入代碼中。我面臨的問題是,在訪問我的代碼中的.txt文件後,我不知道如何在程序讀取文件時解析每行數據的各個字段。我試圖將每行的值存儲到準備好的變量表中,將行中的數據解析回SqlServer數據庫,然後移至下一行並重復。這是我目前擁有的代碼塊。 if語句跳過了不重要的文件行,else語句是我想要解析每行數據的地方。如何解析從c中的.txt文件中拉出的字符串中的單個數據字段
StreamReader reader = new StreamReader(fileLocation);
string strAllFile = reader.ReadToEnd().Replace("\r\n\n", "\n").Replace("\r\n", "\n").Replace("\n\r", "\n");
string[] arrLines = strAllFile.Split(new char[] { '\n' });
int i = 0;
if (strAllFile.IndexOf("Annualized Production") >= 0) //parse that way
{
while (i < arrLines.Length)
{
FileToParse RNIC = new FileToParse();
string test = arrLines[i];
if (test.IndexOf("\fPROD13") >= 0) //skip to useful info
{
i = i + 5;
}
else //do everything else
{
//create the populated model to be returned
i++;
}
這是我使用的存儲值解析
public class Example
{
public int UserID { get; set; }
public int BranchID { get; set; }
public int CompanyID = 1;
public int WritingNumberID { get; set; }
public int ProductID { get; set; }
public string WritingNumber { get; set; }
public string BranchName { get; set; }
public string ProductName { get; set; }
public decimal NetHouseholdSales { get; set; }
public decimal RefundPercentage { get; set; }
public decimal GrossInitialPremium { get; set; }
public decimal NetPremium { get; set; }
public decimal BaseNetPremium { get; set; }
public decimal RefundAmount { get; set; }
public int Applications { get; set; }
public int BankDraftApps { get; set; }
public int ApplicationsSplit { get; set; }
public int BankDraftAppsSplit { get; set; }
public int QtyOfRefunds { get; set; }
public int QtyOfBankDraftRefunds { get; set; }
public int QtyOfRefundsSplit { get; set; }
public int QtyOfBankDraftRefundsSplit { get; set; }
}
手頭的另一個問題是,不是文件中的每一行包含相同的數據類型的變量表中,有3條線在包含有用數據的時候,第一行包含一個集合,接下來的兩行包含相同的第二個集合,但不同的開始變量除外。
這將取決於每行文本中數據的排列方式。有兩種主要的方法在一個文本行中設置表格數據,字符分隔和固定長度字段。字符分隔的地方是字段由特定字符分隔的地方,例如,逗號,管道或任何字符決定。固定長度是每個字段在行中被分配了一定數量的字符的位置,並且如果它們沒有被全部使用,則填充字符填充該字段的其餘部分。 – Kevin
你應該創建一個'var parseList = new List();'然後在while循環內部,你將要填充列表並將它的記錄存儲到一個單獨的列表中 –
MethodMan
@MethodMan我可以很容易地創建列表,然而,這是我第一次使用任何類型的解析體驗。我到底如何填寫清單? – cjbsimtrac