I programmed a c# application that can work on any other computer so i used from sqlite database.I want to backup and restore data in this app.for backup it's ok.I use from below code:
private void button1_Click(object sender, EventArgs e)
{
using (var source = new SQLiteConnection("Data
Source=bazarganidb.db;version=3"))
using (var destination = new SQLiteConnection("Data Source=" + textBox1.Text + "/" + DateTime.Now.ToString("yyyyMMdd") + "backup.db"))
{
source.Open();
destination.Open();
source.BackupDatabase(destination, "main", "main", -1, null, 0);
}
}
But i dont know about restore.how can i restore the database wichi backuped?
I searche alot but no result.
Try this code
class Program
{
private static readonly string filePath = Environment.CurrentDirectory;
static void Main(string[] args)
{
var filename = "bazarganidb.db";
var bkupFilename = Path.GetFileNameWithoutExtension(filename) + ".bak";
CreateDB(filePath, filename);
BackupDB(filePath, filename, bkupFilename);
RestoreDB(filePath, bkupFilename, filename, true);
}
private static void RestoreDB(string filePath, string srcFilename, string
destFileName, bool IsCopy = false)
{
var srcfile = Path.Combine(filePath, srcFilename);
var destfile = Path.Combine(filePath, destFileName);
if (File.Exists(destfile)) File.Delete(destfile);
if (IsCopy)
BackupDB(filePath, srcFilename, destFileName);
else
File.Move(srcfile, destfile);
}
private static void BackupDB(string filePath, string srcFilename, string
destFileName)
{
var srcfile = Path.Combine(filePath, srcFilename);
var destfile = Path.Combine(filePath, destFileName);
if (File.Exists(destfile)) File.Delete(destfile);
File.Copy(srcfile, destfile);
}
private static void CreateDB(string filePath, string filename)
{
var fullfile = Path.Combine(filePath, filename);
if (File.Exists(fullfile)) File.Delete(fullfile);
File.WriteAllText(fullfile, "this is the dummy data");
}
}
For restore just use something like this :
string BackupPath = "Backup/Backup.db";
string restorePath = "Mydb.db";
File.Copy(BackupPath, restorePath, true);
//copy has three parameters : string SourceFileName,string DesFileName,bool Overwrite
Related
My Project is in ASP.NET MVC, Right now I am using Razor Engine Service (RazorEngineService.RunCompile) to create multiple XML files and making it as a single Zip file and exporting it.
But the problem is that when we pass the model object each time to process the template and return it as separate XML files and completing the whole operation it takes more time to complete (Almost ~40 Seconds for 10 objects) for whole content to export.
Is there anything wrong with my current approach or am I doing it correctly right now? Please guide me If I am doing any mistakes in this approach.
private FileInfo Export(List<Model> modelList)
{
string timeStr = Datetime.Now.ToString();
string archiveFileName = "Main.zip";
string archivePath = Path.Combine(_reportFolderPath, archiveFileName);
using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create))
{
foreach (var list in modelList)
{
string fileName = model.name + model.Id;
string filePath = GetModelExport(list, fileName, timeStr);
archive.CreateEntryFromFile(filePath, fileName + ".xml");
}
archive.Dispose();
}
return new FileInfo(archivePath);
}
private string GetModelExport(Model model, string fileName, string timeStr)
{
var processedTemplate = ProcessTemplate(model, TemplateName, TemplateKey);
string reportFilelName = fileName + "_" + timeStr + ".xml";
string filePath = Path.Combine(_reportFolderPath, reportFilelName);
using (var file = new StreamWriter(filePath))
{
file.Write(processedTemplate);
}
return filePath;
}
private string ProcessTemplate(Model model, string templateName, string templateKey)
{
var templateFilePath = Path.Combine(_reportTemplateFolder, templateName);
return ReportUtils.ProcessTemplate(templateFilePath, templateKey, model);
}
public static string ProcessTemplate(string templatePath, string templateKey, object model = null)
{
var templateService = RazorEngineService.Create();
var result = templateService.RunCompile(File.ReadAllText(templatePath), templateKey, null, model);
return result;
}
some of your code is missing so i cant see the whole picture, this is what i would start with..... gd luck.
public class HolderTempName
{
private TemplateService _templateService;
private Dictionary<string, string> _templateContainer;
public HolderTempName()
{
//this will save creating this everytime
_templateService = RazorEngineService.Create();
//this will hold the template so it does not have to fetch on each loop,
//if the same template is used.
_templateContainer = new Dictionary<string, string>();
}
//you will need to tweeek this to get the type out
private string GetTemplate(string templateName, templatePath)
{
if(!_templateContainer.Conatains(templateName))
{
var text = File.ReadAllText(templatePath);
_templateContainer[templateName] = text;
}
return _templateContainer[templateName];
}
private FileInfo Export(List<Model> modelList)
{
string timeStr = Datetime.Now;
string archiveFileName = "Main.zip";
string archivePath = Path.Combine(_reportFolderPath, archiveFileName);
using (ZipArchive archive = ZipFile.Open(archivePath, ZipArchiveMode.Create))
{
foreach (var item in modelList)
{
var templateFilePath = Path.Combine(_reportTemplateFolder, TemplateName); //<--TemplateName seems like a local private
//these should come from where cant see where...
var template = GetTemplate( TemplateName, templateFilePath)
string modelResponse = ProcessModel(item,template,TemplateKey ); //<-- why is not passing in the template
//step 2;
//making this above done in parrell and then add aync, but before all that measure what is taking time
string pathname = MakeFileName(_reportFolderPath, reportFilelName, timeStr);
SaveToDisk(pathname, modelResponse);
string fileName = model.name + model.Id;
archive.CreateEntryFromFile(filePath, fileName + ".xml");
}
archive.Dispose();
}
return new FileInfo(archivePath);
}
private string MakeFileName(string path ,string filename, string tStamp)
{
string reportFilelName = fileName + "_" + timeStr + ".xml";
string filePath = Path.Combine(_reportFolderPath, reportFilelName);
return filePath;
}
private void SaveToDisk(string filePath, string content)
{
using (var file = new StreamWriter(filePath))
{
file.Write(processedTemplate);
}
}
public static string ProcessTemplate(object model, string template, templateKey)
{
var result = templateService.RunCompile(template, templateKey, null, model);
return result;
}
}
I need a copy file on folder to another folder and i'm use this
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string file in files)
{
folderBrowserDialog1.ShowDialog();
string xx = folderBrowserDialog1.SelectedPath;
folderBrowserDialog1.ShowDialog();
string yy = folderBrowserDialog1.SelectedPath;
File.Copy(xx, yy);
But is not working.
Why?
Try this code.
I assume you want to read a file then write it to new one.
Hope it helps.
string sourceFile;
string newFile = "C:\NewFile\NewFile.txt";
string fileToRead = "C:\ReadFile\ReadFile.txt";
bool overwriteExistingFile = true; //change to false if you want no to overwrite the existing file.
bool isReadSuccess = getDataFromFile(fileToRead, ref sourceFile);
if (isReadSuccess)
{
File.Copy(sourceFile, newFile, overwriteExistingFile);
}
else
{
Console.WriteLine("An error occured :" + sourceFile);
}
//Reader Method you can use this or modify it depending on your needs.
public static bool getDataFromFile(string FileToRead, ref string readMessage)
{
try
{
readMessage = "";
if (!File.Exists(FileToRead))
{
readMessage = "File not found: " + FileToRead;
return false;
}
using (StreamReader r = new StreamReader(FileToRead))
{
readMessage = r.ReadToEnd();
}
return true;
}
catch (Exception ex)
{
readMessage = ex.Message;
return false;
}
}
It seems that you do not use filenames in your source code.
I made an example. File copy function.
public void SaveStockInfoToAnotherFile(string sPath, string dPath, string filename)
{
string sourcePath = sPath;
string destinationPath = dPath;
string sourceFile = System.IO.Path.Combine(sourcePath, filename);
string destinationFile = System.IO.Path.Combine(destinationPath, filename);
if (!System.IO.Directory.Exists(destinationPath))
{
System.IO.Directory.CreateDirectory(destinationPath);
}
System.IO.File.Copy(sourceFile, destinationFile, true);
}
//folderBrowserDialog1.ShowDialog();
//string xx = folderBrowserDialog1.SelectedPath;
//string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
//folderBrowserDialog1.ShowDialog();
//string yy = folderBrowserDialog1.SelectedPath;
//foreach (string file in files)
//{
// File.Copy(xx + "\\" + Path.GetFileName(file), yy + "\\" + Path.GetFileName(file));
Using below code, how can I set the code in SQLiteConnetion object ?
public SQLiteConnection dbConnection = new SQLiteConnection();
string fileName = "test.s3db";
string sourcePath = #"E:\File\DMS\DAL\Model";
string targetPath = #"C:\ProgramData\CompanyName\appName";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
}
I want to automatically create a DB path if the path does not exist.
dbConnection = ??
I have this method to copy database:
public static void BackupDatabase(string sourceFile, string destFile)
{
using (SQLiteConnection source = new SQLiteConnection(String.Format("Data Source = {0}", sourceFile)))
using (SQLiteConnection destination = new SQLiteConnection(String.Format("Data Source = {0}", destFile)))
{
source.Open();
destination.Open();
source.BackupDatabase(destination, "main", "main", -1, null, -1);
}
}
I have this code to copy a file to another destination, however I need the users to choose the destination plus the name of file copied is = the old name with the date and hour of my PC ..
string fileToCopy = #"d:\pst\2015.pst";
string destinationDirectoryTemplate = textBox2.Text;
var dirPath = String.Format(destinationDirectoryTemplate, DateTime.UtcNow);
var di = new DirectoryInfo(dirPath);
if (!di.Exists)
{
di.Create();
}
var fileName = Path.GetFileName(fileToCopy);
var targetFilePath = Path.Combine(dirPath, fileName);
File.Copy(fileToCopy, targetFilePath);
This should work
protected void Button3_Click(object sender, EventArgs e)
{
string fileToCopy = #"e:\TestFile.pdf";
string destinationDirectoryTemplate = TextBox1.Text;
var dirPath = string.Format(destinationDirectoryTemplate, DateTime.UtcNow);
var di = new DirectoryInfo(dirPath);
if (!di.Exists)
{ di.Create(); }
var fileName = Path.GetFileNameWithoutExtension(fileToCopy);
var extn = Path.GetExtension(fileToCopy);
var finalname = fileName + " " + string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now) + extn;
var targetFilePath = Path.Combine(dirPath, finalname);
File.Copy(fileToCopy, targetFilePath);
}
I need to create a SSIS script to remove the date from file name. for example file name is: TestFile_122413.CSV I need to rename it to TestFile.CSV. I don't know how to keep file extension and how to deal with the date changes on file. I receive this file every day. Here is my code:
`public void Main()
// TODO: Add your code here
const string DIRECTORY_PATH = #"E:\ScriptsTest";
//const string FILE_NAME_TEMPLATE = "SSS_PROF_010113.CSV";
const string FILE_NAME_TEMPLATE = "*.CSV";
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
File.Move(filePath, filePath.Replace(FILE_NAME_TEMPLATE, FILE_NAME_TEMPLATE.Substring(0,8)));
}
}
}
}`
This should work. BTW, have you tried using the ForEach task? That may be simpler.
public void Main()
{
const string DIRECTORY_PATH = #"C:\temp\";
const string FILE_NAME_TEMPLATE = "*_??????.CSV";
int underscoreAt = 0;
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH,FILE_NAME_TEMPLATE);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
underscoreAt = filePath.LastIndexOf('_');
string newName = string.Format ("{0}.CSV", filePath.Substring(0, underscoreAt));
File.Move(filePath,newName );
}
}
}
}
Check out the SSIS File System Task. It has an operation to rename a file.
Here is a video on how it works.
Hope this helps!
Eric
Try this, it compiles but I haven't run it:
public class Foo
{
public void Main()
{
const string DIRECTORY_PATH = #"E:\ScriptsTest";
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
// Get the file name
string fileName = Path.GetFileName(filePath);
// Get the file extension
string fileExtension = Path.GetExtension(filePath);
// Get the file name without the date part
string fileTitle = fileName.Substring(0, fileName.IndexOf("_"));
File.Move(filePath, DIRECTORY_PATH + #"\" + fileTitle + "." + fileExtension);
}
}
}
}
}