我尝试了这个解决方案,但没有成功。应用程序启动,但一段时间后失败。我不知道该怎么办,你能帮助我吗?我使用 Microsoft.Sqlite.Data 包来解决这个问题,但我不知道如何使用。由于某种原因我无法解决这个问题,但我需要这个来参加学校考试。它告诉我文件名不存在,但它存在。
namespace WpfApp2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
SqliteConnection connection;
ObservableCollection<Orszag> dataList = new();
public MainWindow()
{
InitializeComponent();
}
private void letrehozButton_Click(object sender, RoutedEventArgs e)
{
connection = new($"Filename=adatok.db");
connection.Open();
string createTableText = "CREATE TABLE IF NOT EXISTS orszagok(id INTEGER PRIMARY KEY AUTOINCREMENT, nev VARCHAR(100), terulet INTEGER, nepesseg INTERGER, fovaros VARCHAR(100), fovarosNepesseg INTERGER)";
SqliteCommand command = new(createTableText, connection);
command.ExecuteNonQuery();
foreach (var item in File.ReadAllLines("adatok-utf8.txt", Encoding.UTF8).Skip(1))
{
string[] parts = item.Split(';');
string orszag = parts[0];
int terulet = Convert.ToInt32(parts[1]);
long nepesseg;
if (parts[2].EndsWith('g'))
{
parts[2] = parts[2].Trim('g');
nepesseg = Convert.ToInt64(parts[2]) * 10000;
}
else
{
nepesseg = Convert.ToInt64(parts[2]);
}
string fovaros = parts[3];
int fovarosnepesseg = Convert.ToInt32(parts[4]);
string insertintotext = $"INSERT INTO orszagok(nev, terulet, nepesseg, fovaros, fovarosNepesseg) VALUES('{orszag}', '{terulet}', '{nepesseg}', '{fovaros}', '{fovarosnepesseg}')";
command = new(insertintotext, connection);
command.ExecuteNonQuery();
}
connection.Close();
}
private void readToTable_Click(object sender, RoutedEventArgs e)
{
connection = new($"Filename=adatok.db");
connection.Open();
string queryText = "SELECT * FROM orszagok";
SqliteCommand command = new(queryText, connection);
SqliteDataReader reader = command.ExecuteReader();
dataList = new();
while (reader.Read())
{
int id = reader.GetInt32(0);
string nev = reader.GetString(1);
int terulet = reader.GetInt32(2);
long nepesseg = reader.GetInt64(3);
string fovaros = reader.GetString(4);
int fovarosNepesseg = reader.GetInt32(5);
Orszag newElement = new(id, nev, terulet, nepesseg, fovaros, fovarosNepesseg);
dataList.Add(newElement);
}
resultTable.ItemsSource = dataList;
reader.Close();
}
private void deleteButton_Click(object sender, RoutedEventArgs e)
{
Orszag selected = resultTable.SelectedItem as Orszag;
string deleteText = $"DELETE FROM orszagok WHERE id={selected.Id}";
SqliteCommand command = new(deleteText, connection);
command.ExecuteNonQuery();
dataList.Remove(selected);
}
}
}
使用绝对路径:您可以指定文件的绝对路径,而不是依赖当前工作目录中的文件。这确保应用程序确切地知道在哪里可以找到它。
string filePath = @"C:\Path\To\Your\File\adatok-utf8.txt";
foreach (var item in File.ReadAllLines(filePath, Encoding.UTF8).Skip(1))