這是我在stackoverflow上詢問的第一個問題,非常令人興奮。所以對於我的語法和其他類型的錯誤感到抱歉,如果您糾正錯誤,我將不勝感激。我想編寫一個程序讀取一個csv文件,如果它存在於特定文件夾中,將它存儲在List變量中,添加一些新行並將其寫入同一個文件。這個過程將在一段時間內連續重複。如何讀取和寫入csv文件,當用戶用C#並行打開Excel文件時?
當程序正在讀取和寫入文件時,如果用記事本打開它,它不會給出錯誤,程序可以並行訪問文件。但是,如果它是用Office Excel打開的,程序會給出錯誤提示「文件訪問被拒絕,因爲它被另一個進程使用..」。我想問你:
1)是否有可能給程序優先,所以程序仍然可以訪問文件,但用戶不能?或者程序和用戶都可以訪問文件嗎?
2)如果解決方案是用記事本打開文件,有沒有辦法將這個文件的默認程序設置爲記事本?或者我如何將Csv文件的默認程序更改爲C#中的記事本?代碼
閱讀和寫作部分是波紋管:
List<string> csvLines = new List<string>();
string address = folderpath + @"\PLC_LOGLARI";
if (!Directory.Exists(address))
Directory.CreateDirectory(address);
string fileAddress = address + @"\" + fileName + "_" + machineNo + "_1.csv";
if (Directory.EnumerateFiles(address).Any(f => f.Contains(fileName + "_" + machineNo)))
{
string[] addressArray = Directory.GetFiles(address, fileName + "_" + machineNo + "*.*");
FileInfo fileInformation = new FileInfo(addressArray[addressArray.Length - 1]);
long fileSize = fileInformation.Length;
if (fileSize > 5000000)
{
int fileNo = int.Parse(addressArray[addressArray.Length - 1].Substring(addressArray[addressArray.Length - 1].LastIndexOf('_') + 1, 1)) + 1;
fileAddress = addressArray[addressArray.Length - 1].Substring(0, addressArray[addressArray.Length - 1].LastIndexOf('_') + 1) + fileNo.ToString() + ".csv";
}
else
{
fileAddress = addressArray[addressArray.Length - 1];
csvLines = File.ReadAllLines(address).ToList();
}
}
else
{
string[] headings = makeHeadings();
csvLines.Add(headings[0]);
csvLines.Add(headings[1]);
}
string newLine = "";
// some operations and calculations for newLine
// some operations and calculations for newLine
// some operations and calculations for newLine
newLine = newLine.Substring(1, newLine.Length-1);
csvLines.Add(newLine);
File.WriteAllLines(fileAddress, csvLines.ToArray());
感謝您的幫助。
由於您正在編寫日誌文件,您是否考慮過任何可以幫助您的常見現有庫,以避免您現在遇到的許多缺陷? – oerkelens
至於讀取正在寫入的日誌文件,請考慮使用Notepad ++。它基本上是您的標準記事本,但是在類固醇。它所做的一件有用的事情是,它在文件發生變化時通知您並允許您重新加載它 - 因此您可以非常輕鬆地監視日誌。將擴展名從.csv更改爲.log或.txt將停止Excel打開文件,順便說一句。 – oerkelens
感謝您的回覆。實際上,它爲每個新行寫入二進制格式的文件36字節,這意味着288列,並且週期爲500毫秒,所以文件中有太多的行和列,查看數據的最佳方式是使用Excel我想,這就是爲什麼我選擇csv擴展。 – Baacus