简体   繁体   中英

Connecting to MS access database

I recently started learning C# WPF (using MS VS 2013 express) and I´ve tried to connect to my access database without any success, the problem I have is that whenever I try to make a connection I get this exception "Not a valid file name" .

I realized later than I should have (and after a ton of googling on the matter) that it must have had something to do with my connection string that follows :

connect.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=‪D:\\Google Drive\\Programmering\\C#\\WpfApplication3\\WpfApplication3\\bin\\Debug\\sensors\\MPU6050.accdb; 
Persist Security Info=False;";

And this path is copied from the properties/security tab of the file so that should be correct. I have also tried with

connect.ConnectionString ="Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=‪D:\Google Drive\Programmering\C#\WpfApplication3\WpfApplication3\bin\Debug\sensors\MPU6050.accdb; 
Persist Security Info=False;";

Which is the same but excluding the @ in the beginning.

I have tried to debug it as Any CPU, x64 and x86 and the only difference is that the 2 latter options returned the following exception as soon as I ran the application before even manually triggering the event that tried to connect to my database.

An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code

Additional information: Could not find a part of the path 'D:\\Google Drive\\Programmering\\C#\\WpfApplication3\\WpfApplication3\\bin\\x64\\Debug\\sensors'.

I assumed that this exception var pretty much the same as when I debugged it as Any CPU.

Here is my C# code MainWindow.xaml.cs and my XAML code isn´t relevant as I have everything regarding the database in my code behind. (as far as I know) It will probably seem like a joke to you but as I said earlier I'm just starting out with WPF (and C#) and I myself already know that I could of handled things more effective in some ways.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports;
using System.IO;
using System.Data.OleDb;
using System.Data;
using System.Windows.Threading;

namespace WpfApplication3
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            avbComPort.Text = "COM Port";
            addSensors();            

            foreach (string s in SerialPort.GetPortNames()) 
            {
                ComboBoxItem cbi = new ComboBoxItem();
                cbi.Content = s;
                avbComPort.Items.Add(cbi);
            }
        }

        public void addSensors()
        {
            string dynamicPath = System.IO.Directory.GetCurrentDirectory();
            string fullPath = dynamicPath + "\\sensors";
            string[] sensors = Directory.GetFiles(fullPath);
            int fileQuantity = sensors.Length -1;

            for (int i = 0; i <= fileQuantity ; i++)
            {
                string path = sensors[i];
                string[] pathArr = path.Split('\\');
                string[] fileArr = pathArr.Last().Split('.');
                string fileName = fileArr.First().ToString();
                MenuItem sensor = new MenuItem {Header = fileName};
                sensor.Click += new RoutedEventHandler(sensor_Click);
                confSensors.Items.Add(sensor);

            }
        }

        public void sensor_Click(Object sender, RoutedEventArgs e)
        {
            MenuItem sensor = sender as MenuItem;
            TabItem tab = new TabItem { Header = sensor.Header, Width = sensorTab.Width, Height = sensorTab.Height };
            DataGrid dataLog = new DataGrid() { Name = "dataLog", IsReadOnly = true, Width = 300, Height = 500, HorizontalAlignment = 0, VerticalAlignment = 0, AutoGenerateColumns = true, ItemsSource = "Binding"};

            string filePath = System.IO.Directory.GetCurrentDirectory() + "\\sensors" + sensor.Header + ".accdb";

            try //code regarding the database connection
            {
                OleDbConnection connect = new OleDbConnection();
                connect.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=‪D:\\Google Drive\\Programmering\\C#\\WpfApplication3\\WpfApplication3\\bin\\Debug\\sensors\\MPU6050.accdb; Persist Security Info=False;";
                connect.Open();
                dbStatusLbl.Content = "Connection to database established successfully";
                connect.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show("A problem occured while trying to establish a stable connection to the database:  " + ex.Message, "A wild error has appeared", MessageBoxButton.OK, MessageBoxImage.Error);
            } // end of that code
            Grid grid = new Grid() { Height = tab.Height, Width = tab.Width};
            grid.Children.Add(dataLog);
            tab.Content = grid;
            sensorTab.Items.Add(tab);
        }

        private void sensorTab_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        }
    }
}

I have also tried to obtain the file name programmatically with these snippets

string filePath = System.IO.Directory.GetCurrentDirectory() + "\\sensors" + sensor.Header + ".accdb";

connect.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|filePath|‪; Persist Security Info=False;";

Where \\\\sensors is the folder inside my bin\\debug folder and sensor.Header comes from the public void addSensors() method and that has worked explicitly in a previous context where I stored information in .txt files instead of MS access db, as you see this would result in the same string as the full-path and as expected, it returns the exact same exception.

Furthermore I have Office 2013 64 bit, Windows 10, and Visual Studio 2013 express for desktop, all drivers updated.

I have tried everything I can imagine and searched the web for hours now and this is my last resort, if you could help even by just sending a link to a possibly helping webpage I would be grateful. Thanks in advance and sorry for my English as it´s not my first language.

EDIT I did not have MS Access open while trying to connect with it as I understand that it uses some sort of protection whilst being open?

I've solved it! And I'm kind of embarrassed because I have experienced this before but it never crossed my mind this time since I never switched computer.

The problem was that when Google Drive Synchronizes my files it sometimes "f*ck a bit" and renames folders to "sensors(1)" instead of the original name "sensors" which leads to the conclusion that sometime between me getting the file path and trying to run the application Google Drive changed the name of the folder And therefore the path was indeed not valid, Thanks to everyone that tried to help especially the 2 that edited my question because i'm quite new here and still learning even how to format my questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM