Making a file backup program - c#

Where I work, I test software, we put a new build of the software on the server each day, I need to be able to save a copy of the build and renaming it for the date it was saved, how would I do this?
(the start and destination locations will be the same each time)
The file is just an installer kinda, it is all self contained.
I need it to access the date the original was created on, so I do not have the problem with multiple files of the same name, and making it easy to find the build I need.

From msdn:
string path = #"c:\temp\MyTest.txt";
string path2 = path + "temp";
try
{
// Create the file and clean up handles.
using (FileStream fs = File.Create(path)) {}
// Ensure that the target does not exist.
File.Delete(path2);
// Copy the file.
File.Copy(path, path2);
Console.WriteLine("{0} copied to {1}", path, path2);
// Try to copy the same file again, which should succeed.
File.Copy(path, path2, true);
Console.WriteLine("The second Copy operation succeeded, which was expected.");
}

Are you talking about running perhaps a batch script or vbscript type file to do this automatically? That's about the easiest way to do it that I can think of. However, I may be oversimplifying your situation, so just let me know. I can provide you with some example code on how to do this via a .bat or vbscript file.

I would create a new folder containing the date in the name (like "Build_2012_06_07") for each build and move all the files (.exe, .dll, .pdb etc.) belonging to a build to this folder without renaming the files.

Related

How to get directory of an xls file C#

I need to make a program that reads the columns of an excel. But for that, I need to get the path (directory) of this excel. What prevents me from doing this, is that I didn't want to leave my local directory fixed, because if someone downloads the file on another machine, they will need to change the path.
You asked How to get directory of an xls file C#.
As others have pointed out, the file needs to be in a known location and one way to do that is to add the Excel file to your solution and mark it as Content, specifying that it should be copied to the output directory. The image below shows how to set these properties.
You also seem to be looking for a robust way to make this happen when you deploy the app for other users. For this, you will need a strategy for making an .msi or .msix that will place this file where it needs to be. But to answer your basic question the way you asked it the path in this case can be obtained in this manner. This code will get the path and open the Excel file.
// Get the path and open the Excel file
static void Main(string[] args)
{
var path =
Path.Combine(
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
"Microsoft Excel Worksheet.xlsx");
Console.WriteLine(path);
System.Diagnostics.Process.Start("explorer.exe", path);
}
I should mention that a file in the executing directory can be read but not written (without elevated permissions). If the file is user data then refer to the answer that uses an Environment variable:
var appdata = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
You have two options:
If you don't want to your excel files to be stored in your application's directory, you can simply put things in the root of your C: partition. Every windows device is gonna have the C: partition. As the user Lee Taylor has pointed out, it turns out you can have a windows device without the C: partition, although uncommon
If you don't mind having your excel files stored in your application's directory, you can get the relative path of your application's directory throughPath.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
There are other ways but I believe these are the simplest and easiest to do.
If you just need to dynamically get the path to a file that is in the same project directory, then the following code works for me -
string filePath = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "\\excel\\Prices.xlsx";
where "\excel" is the folder in my project and "\Prices.xlsx" the file in the project

File.Exist always return false

I know it's been asked a lot already, but I still can't get my code to work.
I built a little programm which lets you choose a product and asks for your information if you want to buy it. Every time the given information like name, address and so on... is saved in a single Excel file.
Now I want this file to be created if it doesn't already exists. It works to create one, and overwrite it. But if it exists, File.Exist will return a false anyway and overwrite the entire file with a new blank. It get's created to [user]\Documents folder.
My idea to check if the file already exists was this:
if (!File.Exists(#"C:\Bestellungen.xlsx"))
{
CreateNewHistory(); // Method which creates the file in correct format
}
WriteData(); // Method to write given information to correct cells
The method for creating the file is simply:
private void CreateNewHistory()
{
Excel excel = new Excel();
excel.CreateNewFile();
excel.SaveAs(#"Bestellungen.xlsx");
...
// some cells get writte here, just for format
...
excel.Close();
}
"Bestellungen" is German for "orders"... ;)
I suppose it has something to do with the way I pass the path into File.Exist but I am just clueless. I tried to copy the file into the bin\debug folder of my project. If it's there it works perfectly, but i really would like to know how i can find the file in the documents folder. I already tried put the absolute path, but it's always returning false.
If you need more information about the code let me know, I'm really new to c# or coding basically.
You're saving the file using a relative path. The file will be saved in the program's working directory. Using C:\ will never work. In fact, you can't even write to the root folder without elevated privileges. Program Files is another folder you can't (and shouldn't even try) to save into, since 1995.
Older Windows versions would just throw an exception. Some developers would try to force permissions instead of fix their bugs, so newer versions redirect inappropriate writes to eg Documents or APPDATA. I suspect you run your program from Program Files and the OS redirected the file save operation to Documents.
You should use an absolute path to save files in the correct folder. User documents go to Documents, application files go to APPDATA etc. You can get the absolute path to each of those locations with Environment.GetFolderPath, and one of the SpecialFolder values like Desktop or MyDocuments eg :
var docFolder=Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filePath=Path.Combine(docFolder,"Bestellungen.xlsx");
excel.SaveAs(filePath);
And retrieve it the same way:
var docFolder=Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filePath=Path.Combine(docFolder,"Bestellungen.xlsx");
if (!File.Exists(filePath))
...
The SpecialFolder enumeration explains the purpose of the various folders:
MyDocuments contains document files for the current user,
Desktop points to the current user's desktop
ApplicationData and LocalApplicatinoData contain application-specific files used by the current user, like logs and settings etc.
CommonDocuments, CommonDesktop, CommonApplicationDatacontain files used by all users on a computer
Use the Document folder to save your file.
Get the User Document Folder
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Set the Filename
string file="Bestellungen.xlsx";
Finally, generate your actual path
String absolutePath = System.IO.Path.Combine(path , file);
its throw a exception due to permission issue
please change directory or give proper permission

C# restore previous directory

I currently have a FileHandler.cs class which does various things with a file. The default directory for C# running within VisualStudio is Project/bin/Debug or Project/bin/release depending on which you are running. As such in the constructor of my file class I do the following:
System.IO.Directory.SetCurrentDirectory("..\\..\\TextFiles");
to go from either bin or debug to the main folder where I have my TextFiles folder. The issue with this is the next time I create a FileHandlerthe working directory goes up 2 more levels where TextFiles doesn't exist.
How can I set the working directory to the default bin/debug again without using an absolute path?
There are several hacks I could use such as making it static or incremnting a counter for each FileHandler created and raising the current directory by 2 levels for each one past the first, but both those solutions are rather messy.
Thanks, Kalen
I would not rely on the default directory. It can change depending on how the application starts. Instead, you can try to detect location of the executable and use it to construct the data path. Something like this:
var exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
// or AppDomain.CurrentDomain.BaseDirectory, see http://stackoverflow.com/a/837501/3246555
var dataPath = Path.Combine(exePath, #"..\..\TextFiles");
//Directory.SetCurrentDirectory(dataPath);
Also, it might be better to avoid SetCurrentDirectory and construct the full file path instead:
var filePath = Path.Combile(dataPath, "MyFile.txt");

Difference between File.Copy and File.Move

Nowadays I am dealing with a small application which updates the mssql's compact database files on an iss server.
I've preferred to use SSIS to organize the flow. For couple of days it worked well, but then started to give errors.
In SSIS I've used the "File System Task"s "Move File" operation to move generated files from a folder to iss server's shared folder. If it fails, in case of a locked file, it tries it later. But I've seen that sometimes the files in the destination folder started to disappear.
Then I've decided to write custom code. I've removed the "File System Task" and put a "Script Task" instead of it. And write a couple of lines in it.
string destinationFile, sourceFile;
destinationFile = Path.Combine(Dts.Variables["FileRemoteCopyLocation"].Value.ToString(), Dts.Variables["CreatedFileName"].Value.ToString());
sourceFile = Path.Combine(Dts.Variables["OrginalFilePath"].Value.ToString(), Dts.Variables["CreatedFileName"].Value.ToString());
bool written = false;
try
{
File.Copy(sourceFile, destinationFile, true);
File.Delete(sourceFile);
written = true;
}
catch(IOException) {
//log it
}
if (written)
Dts.TaskResult = (int)ScriptResults.Success;
else
Dts.TaskResult = (int)ScriptResults.Failure;
It worked well. But I tried it by locking the destination file. I've connected the destination file in Sql Server Management Studio (it is an sdf file). And surprizingly it works too.
And I've tried it from operating system, by copying the source file and pasting it to the destination. Windows 7 asks me if I want to overwrite it and I say yes and it overwrote the file (copy and replace) I use with another process, no warning no error.
But if try to rename or delete it does not let me to do that. Or if I try to cut and paste it (Move and Replace) it says "you need permission to do this action".
As I understood, "Copy, delete" and "Move" are totally different things. And I still can not understand how can I overwrite a locked file.
Any ideas?
File.Move method can be used to move the file from one path to another. This method works across disk volumes, and it does not throw an exception if the source and destination are the same.
You cannot use the Move method to overwrite an existing file. If you attempt to replace a file by moving a file of the same name into that directory, you get an IOException. To overcome this you can use the combination of Copy and Delete methods
Answer orignal from : Difference between in doing file copy/delete and Move
Although the subject is not new, I would like to share my experience. I had to change the pdf file names in my digital library. When I copied about 10,000 legal articles to another folder by changing their names using the File.Copy() method, half of it took about 15 minutes, and I stopped the process because of it takes so long. Then when I tried the same thing with the File.Move() method, the result was incredible for me: It took less than 1 minute to move the whole thing. Of course, I don't need to say that all these are directly related to the system features.

FileInfo CopyTo method throwing an IOException (.net)

The CopyTo method of FileInfo class throws an IOException
The process cannot access the file 'C:\Data\Test.XML' because it is being used by another process.
Any ideas on why this should happen? I understand that copying a file just requires read access. So ideally even if the file is write protected or is opened by some other program the CopyTo should have no problem executing.
FileInfo copyFile = null;
//currentFile.FileInformation is of type FileInfo which is referring to the file for which a copy is being created. In this case it is C:\Data\Test.XML
System.IO.FileInfo file = new FileInfo(currentFile.FileInformation.FullName);
// Constructing name for the temporary copy of Test.XML
string newName = "Temp Copy of " + currentFile.FileInformation.Name;
//This is where I get the exception. The CopyTo fails...
copyFile = file.CopyTo(System.IO.Path.Combine(currentFile.FileInformation.DirectoryName, newName), true);
fs = System.IO.File.Open(copyFile.FullName, FileMode.Open);
Also some important points to note :
I have write access to the folder to which I am trying to copy. This is happening with only certain files.
The file for which I am trying to create a copy of is not Read-only.
Please let me know if I can provide you with any more details
Thanks in advance
Download sysinternal's process explorer
put a breakpoint on File.CopyTo
in process explorer, search for the file name, it will tell you which process got it open
Another process might have specified the FILE_SHARE_READ mode when it opened the file, which would prevent you from even reading it.
You can use Process Explorer to find that process.
If you're using Windows, try using Process Explorer to determine what process is using the files you are trying to copy.

Categories

Resources