How to copy file from C#.Net - c#

My C#.Net windows Application connects to a SQLServer2005 database and implements database backup functionality.
In my Application,
I try to perform a file copy like this:
<!-- language:lang-csharp -->
File.Copy(Application.StartupPath + "\\dbSTK.mdf", "D:\\dbSTK123.mdf",true);
but it throws an exception with the following message:
" The Process cannot Access the File, because it is being use by another Process"
How can I copy the db file which is already in use?

You cannot copy mdf file while SqlServer is running. Just temporary shut SqlServer down or Detach that database (here) before copying.

Rather that copy the actual MDF, it's probably a better idea to backup the MDF using SQL Server's built in BACKUP command.
The suggestions to detach the database and then copy it are problematic because it takes your database offline.

The server denies inteprocess access to data files. Once it has opened a data file no other process can open one too. That's why your function fails.

You should close all open connections to DB to access the DB file. But generally, you should not touch the database file. You'd better use SQL command to back up the database.
string backupCommandText = "BACKUP DATABASE [<YOUR_DB_NAME>]" +
"TO DISK = N'<BACKUP_PATH>' WITH NOFORMAT, NOINIT, " +
"NAME = N'Web-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = backupCommandText ;
cmd.Connection = conn;
cmd.ExecuteNonQuery();

Related

I am trying to connect my windows form application with a ms access database with a mdb file, how do I get past this error

The file does exist at this path, it is a mdb file. However the system is saying that it does not recognise the file, the following error is coming up
System.Data.OleDb.OleDbException: 'Could not find file 'C:\Users\shera\Desktop\repos\Elevator\Elevator\bin\Debug\net6.0-windows\elevator-Records.mdb
var DBPath = "elevator-Records.mdb";
conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + DBPath);
conn.Open();
System.Windows.Forms.MessageBox.Show("Connected successfully");
My suggestion for you is ADO.NET wey
You should go to your database and write
Insert commands or update or delete an paste in your string
In this wey you should using SQL commands
In top of your class
You should go search in net to know ADO.NET

When I update the database with a new row from the browser, why isn't the SQL Server database table updated? [duplicate]

What is the proper way to create a local-database file and then connect the app to it ? I want it to work even if you change the location of the project folder.
Right know what I do is: Project -> Add new item -> Service-based Database and I create one and then I go to Data -> Add new Data Source, I add the created database and I get the connection string.
Ok, all good, I can connect to it as I wish BUT all my data is erased from the database when I close the application (not always).
For example, this code:
SqlConnection c = new SqlConnection(#"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DB.mdf;Integrated Security=True;User Instance=True");
c.Open();
SqlCommand cmd;
cmd = new SqlCommand("CREATE TABLE Persons (id int primary key, nume char(20), age int)");
cmd.ExecuteNonQuery();
cmd = new SqlCommand("INSERT INTO Persons VALUES (#id, #name, #age)", c);
cmd.Parameters.AddWithValue("#id", 1);
cmd.Parameters.AddWithValue("#name", "Catalin");
cmd.Parameters.AddWithValue("#age", 20);
cmd.ExecuteNonQuery();
I run it first time to create the table and add an item to it and then, then if I run it the second time without the sqlcommand to create the table persons, it tells me that there is no Persons object, BUT if I run the second time the project with the same code, it tells me that there is already a Persons object...
I am using Visual C# Express Edition 2010.
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
Change the Copy to output directory setting from Copy always to Copy if newer in the property page for your database files. Every time you run the application the new database file is copied from your project to the bin folder, so all of your datas from the previous run are removed.
More: https://msdn.microsoft.com/en-us/library/ms246989.aspx
I figured out a pretty simple answer but maybe it's not the best use to do it this way.
Anyway, I add the database to the project and then I connect directly to it by doing so:
string path = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory)));
SqlConnection c = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=""" + path + #"Database1.mdf"";Integrated Security=True;User Instance=True");
This way, if you move your project between multiple PCs, the connection will still work (I needed this the most).
This also works with .SDF files and it's easier too.

Backup a remote SQL Server database

I want to backup my remote SQL Server database onto the local computer.
So far I've tried:
using (SqlConnection defaultSqlConnection = new SqlConnection(Constants.Database_Constants.GetConnectionStringFromProfile(Constants.Profiles.Staging)))
{
string pathDatabase = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\backup_production_database"+DateTime.UtcNow.ToString("d_MMM_yyyy_HH_mm_ss", CultureInfo.InvariantCulture)+".bak";
WriteLine("The backup will be stored in " + pathDatabase);
string backupDb = "BACKUP DATABASE DB_Staging TO DISK = '" + pathDatabase+ "' WITH INIT, COMPRESSION";
File.Create(pathDatabase);
using (SqlCommand backupCommand = new SqlCommand(backupDb, defaultSqlConnection))
{
defaultSqlConnection.Open();
backupCommand.ExecuteNonQuery();
}
}
But I get this error :
Cannot open backup device 'XXXX\bin\Debug\backup_production_database22_Mar_2017_08_04_42.bak'.
Operating system error 3(The system cannot find the path specified.).
BACKUP DATABASE is terminating abnormally.
I know that I could generate a script using SQL Server Management Studio but it doesn't help me. I want to backup my database in a powershell script automatically without having to go manually into SQL Server Management Studio
You cannot create a directly backup from a remote server to a local disk.
Please look this link.

Microsoft Access list all database

I need to fetch all databases of Microsoft Access in localhost.
On clicking the database name I have to list the tables
I can able to fetch the tables for a particular database.
My problem is I cant able to list out the MS Access databases available in localhost
please suggest me the ideas to start coding
I tried
OleDbConnection con; // create connection
OleDbCommand com; // create command
OleDbDataReader dr; //Data read for read data from database
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source =D:\mydb.mdb");
com = new OleDbCommand("Select * from Table1",con);
con.Open(); // open the connection dr = com.ExecuteReader();
expected result:
with out mentioning Data Source =D:\mydb.mdb" i have to list all ms access databases of
localhost
All available databases like
database1.accdb
database2.accdb
Access (or Jet, to use the name of the database engine) doesn't run a server, in the way that Sql Server or MySql do. An Access database is simply a file of particular format that is loaded on request, but the Jet engine libraries.
For this reason, there's no simple way to find all databases on a local machine: you would need to scan all files on the machine for .accdb or .mdb extensions. More likely, you should ask the user to select a specific file or scan a specified subfolder, since searching the whole machine will likely take a prohibitively long time.

OS error 3 when backing up database

It is a follow-up question to my previous question in the same forum.
I would like to take a backup of my SQL Server database. Here is the code, for the backup in C#.
userConn = new SqlConnection(userdatabase);
userConn.Open();
string UserString;
UserString = "BACKUP DATABASE #DBName TO DISK = #FilePath";
String destPath = DestDirectory + "\\UserDataTable.bak";
SqlCommand cmd = new SqlCommand(UserString, userConn);
cmd.Parameters.AddWithValue("#dbName", userConn.Database);
cmd.Parameters.AddWithValue("#FilePath", destPath);
cmd.ExecuteNonQuery();
cmd.Dispose();
However, it throws an SQLException,
"Cannot open backup device
'D:\BookKeeping\Database\11_01_2013_21_15\Database\UserDataTable.bak'.
Operating system error 3(failed to retrieve text for this error.
Reason: 15105). BACKUP DATABASE is terminating abnormally."
Any Idea, what could be wrong ?
Thanks a lot for your time and your help.
"Operating system error 3" means that the directory was not found. SQL will not create the backup directory for you; you have to manually create it before running the backup command.
Make sure your SqlServer and the location where you want to create a backup is the same system. If you are using sqlServer remotely(Not located in your system) then you can not create a backup in your machine or you can not restore the database taking a .bak from your machine also.

Categories