[英]Saving and reading a file into a data table - C#
我對此很陌生,所以請多多包涵。 我正在嘗試創建一個可以打開文件,加載文件然后將數據填充到表中的應用程序。 我已經設法將其硬編碼到所需的測試文件中,但是現在需要能夠打開具有相同擴展名的任何文件。
到目前為止,我已經包含了代碼。 感謝有人可以指出我正確的方向:)謝謝,喬
OpenFileDialog ofd = new OpenFileDialog();
private void Button3_Click(object sender, EventArgs e)
{
ofd.Filter = "evtx|*.evtx"; //Only allows evtx file types to be seen and opened
if (ofd.ShowDialog() == DialogResult.OK) //Opens the file dialog on button click
{
this.fileNameTextBox.Text = ofd.FileName;
saveFileNameTextBox.Text = ofd.SafeFileName;
}
}
private void loadFileButton_Click(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add("Level");
dt.Columns.Add("Logname");
dt.Columns.Add("Event ID");
dt.Columns.Add("Date and Time");
using (var reader = new EventLogReader(@"C:\Users\Jason\Desktop\Event logs\Security.evtx", PathType.FilePath))
{
EventRecord record;
while ((record = reader.ReadEvent()) != null)
{
using (record)
{
dt.Rows.Add(record.Level, record.LogName, record.RecordId, record.TimeCreated.Value.ToString("dd/MM/yyyy tt:hh:mm:ss"));
}
}
}
tblLogViewer.DataSource = dt;
}
如果我了解您的問題所在,則提示您在Button3_Click()
中Button3_Click()
以下文件:
if (ofd.ShowDialog() == DialogResult.OK) //Opens the file dialog on button click
{
this.fileNameTextBox.Text = ofd.FileName;
saveFileNameTextBox.Text = ofd.SafeFileName;
}
...但是然后在loadFileButton_Click()
您正在使用其他路徑來構造EventLogReader
...
using (var reader = new EventLogReader(@"C:\Users\Jason\Desktop\Event logs\Security.evtx", PathType.FilePath))
{
您已經將所選文件的路徑保存到fileNameTextBox.Text
,因此只需將該屬性傳遞給EventLogReader
構造函數即可。
using (var reader = new EventLogReader(fileNameTextBox.Text, PathType.FilePath))
{
請注意, loadFileButton_Click
假定ofd
先前已顯示並接受(未取消)。 不知道您的不同按鈕是什么,最好在成功提示輸入文件后立即創建並使用EventLogReader
。
if (ofd.ShowDialog() == DialogResult.OK) //Opens the file dialog on button click
{
this.fileNameTextBox.Text = ofd.FileName;
saveFileNameTextBox.Text = ofd.SafeFileName;
using (var reader = new EventLogReader(ofd.FileName, PathType.FilePath))
{
// Use reader...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.