I have a Winforms application with a database. In the app i use a connection string for the database. If i want to use the application on another device, what should I do?
I thought about creating the database from the code at the initial run, but the problem is that I populated that database with data from an excel and I need that data.
4
When your code depends on any location relative to the user or device, the general advice is going to involve using System.Environment
to GetFolderPath()
using the Environment.SpecialFolder
enumeration. Here is a snippet that creates such a path on demand, making sure that the directory is created if it does not already exist.
public string PathOnDevice
{
get
{
if (_pathSingleton is null)
{
_pathSingleton =
Path
.Combine(
System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData),
System.Reflection.Assembly.GetExecutingAssembly().GetName().Name,
"fileName.any");
Directory.CreateDirectory(Path.GetDirectoryName(_pathSingleton ));
}
return _pathSingleton;
}
}
string? _pathSingleton = null;
Another scenario is reading from a file that you have installed with the application in its app directory (that isn’t already embedded as a resource). This wouldn’t be a good place to write anything, however, and I’m just making you aware of this:
AppDomain.CurrentDomain.BaseDirectory;