Error with database file path in project with many databases - c#

I have an error with database file path, the project has many databases with 10 tables, for each file should have 1 database, I create a database but it can't be saved as file ... and the error is:
The File Path Is Not Supported ...
public class filewrite
{
public string datadress, dataname, databaseadress, tablexist, dsname, databak, dataldf, databakldf, filepath, filename;
public filewrite()
{
databaseadress = "baseadress";
dataname = "name";
datadress = "adress";
dsname = "databasename1";
databak = "backUp";
tablexist = "yesorno";
dataldf = "dl";
databakldf = "dbl";
filepath = "path";
filename = "name";
}
public byte writing()
{
if (File.Exists(filepath + #"\" + filename + #"\Data" + datadress))
File.Delete(filepath + #"\" + filename + #"\Data" + datadress);
if (File.Exists(#"C:\tempFile.SMP"))
File.Delete(#"C:\tempFile.SMP");
string path = filepath + #"\" + filename + #"\Data" + datadress;
FileStream fpath = File.Create(path);(The error is in here)
try
{
// read from file or write to file
StreamWriter fwrite = new StreamWriter(fpath);
fwrite.WriteLine(datadress);
fwrite.WriteLine(dataname);
fwrite.WriteLine(databaseadress);
fwrite.WriteLine(tablexist);
fwrite.WriteLine(dsname);
fwrite.WriteLine(databak);
fwrite.WriteLine(dataldf);
fwrite.WriteLine(databakldf);
fwrite.Close();
}
finally
{
}
File.Copy(filepath + #"\" + filename + #"\Data" + datadress, #"C:\tempFile.SMP");
return 10;
}
}

Rather than using filepath + #"\" + filename + #"\Data" + datadress;,
Try using System.IO.Path.Combine instead:
Path.Combine(filepath, fileName, Data, datadress);
which returns a string.

Related

How Change name file after Creation in startup folder?

I With Code my application added to startup
how I can after Creation File (filename + ".url") Change To (filename + ".exe")
static string filename = "troj";
public static string tempure = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + filename + ".exe";
public static string tempurepath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\";
public static void addtostart()
{
try
{
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
if (System.IO.File.Exists(deskDir + "\\" + filename + ".url")) return;
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(deskDir + "\\" + filename + ".url"))
{
string app = tempure;
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=file:///" + app);
writer.WriteLine("IconIndex=0");
string icon = app.Replace('\\', '/');
writer.WriteLine("IconFile=" + icon);
writer.Flush();
}
}
catch
{

IOException when moving an image file

private void MoveFile(string destination, string imagePath)
{
try
{
string source = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["TempImagePath"]);
string[] resizedImage = imagePath.Split('.');
//string compressedImagePath = resizedImage[0] + "_compress." + resizedImage[1];
string thumbnail150Name = resizedImage[0] + "_thumbnail." + resizedImage[1];
string mediumPhoto300Name = resizedImage[0] + "_mediumPhoto." + resizedImage[1];
string largePhotoName = resizedImage[0] + "_largePhoto." + resizedImage[1];
//Move thumbnail
if (System.IO.File.Exists(source + "\\" + thumbnail150Name))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + thumbnail150Name, destination + "\\" + thumbnail150Name);
}
//Move medium sized photo
if (System.IO.File.Exists(source + "\\" + mediumPhoto300Name))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + mediumPhoto300Name, destination + "\\" + mediumPhoto300Name);
}
//Move large photo
if (System.IO.File.Exists(source + "\\" + largePhotoName))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + largePhotoName, destination + "\\" + largePhotoName);
}
//Move original
if (System.IO.File.Exists(source + "\\" + imagePath))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + imagePath, destination + "\\" + imagePath);
}
}
catch (Exception ex)
{
BgLogger.FileLogger.LogError("In private method : MoveFile(string, string), On server : " + Dns.GetHostName() + " At : " + DateTime.Now, ex).Wait();
}
}
I am using this code while moving an image file. But I am getting the following exception
System.IO.IOException: The process cannot access the file because it
is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalMove(String sourceFileName, String
destFileName, Boolean checkHost) at
BgPortal.Controllers.DriverController.MoveFile(String destination,
String imagePath)
https://u3307993.ct.sendgrid.net/wf/open?upn=mzyvlCvUM5odb-2FP3IS9fxavC9Nq-2BVU-2BlgxLxmreq6Qi5SziY4JAfC5R720TrBfTXj7GdvSOgEG2Qeq-2BGKm-2FwWmPOrbAem6UFnvcBKca-2FzIM3XkXg0dHdke9rhjcAKDqtd0MJQCnmyIN-2Fi-2FXbgygtnXFNxuEuwts4hybPsnVR72PsfW4L6YZ32pnlEuwGMF-2Fcg0S8f8Y7UOBHwDMzh1BgJnhqO9i5dgS9LRZytY4n6TNCt37JAtdi5EOj8OxBqhan
This exception occurs very randomly.
Can anyone help me with this?
The exception is thrown because the file you are trying to move is open by your program or another process. Make sure that you are always closing the file after you finish processing it. Particularly, make sure that you always call Close or Dispose on all FileStream objects when they are no longer needed.
If the file is open by another process (for example by another user) then you can wait for some time and retry moving the file.

Using streamwriter but file is always empty

I'm using Streamwriter to save my list data to a text file, but the file is always empty when I open it.
I can get the list to display all of the inputs, so the list works. Heres the code for the filewriter.
private void SaveToFile()
{
string taxpayerLine;
string taxpayerFile;
string myFileName;
FileInfo myFile;
SaveFileDialog taxpayerFileChooser;
StreamWriter fileWriter;
taxpayerFileChooser = new SaveFileDialog();
taxpayerFileChooser.Filter = "All text files|*.txt";
taxpayerFileChooser.ShowDialog();
taxpayerFile = taxpayerFileChooser.FileName;
taxpayerFileChooser.Dispose();
fileWriter = new StreamWriter(taxpayerFile, true);
foreach (Taxpayer tp in Taxpayers)
{
taxpayerLine = tp.Name + "," +
tp.Salary.ToString() + "," +
tp.InvestmentIncome.ToString() + "," +
(tp.InvestmentIncome + tp.Salary).ToString() + "," +
tp.GetRate().ToString() + "," +
tp.GetTax().ToString();
fileWriter.WriteLine(taxpayerLine);
}
fileWriter.Close();
fileWriter.Dispose();
myFile = new FileInfo(taxpayerFile);
myFileName = myFile.Name;
MessageBox.Show("Data Saved to " + myFileName);
}
You can try changing your code like this:
private void SaveToFile()
{
string taxpayerLine;
string taxpayerFile = string.Empty;
string myFileName;
FileInfo myFile;
using (SaveFileDialog taxpayerFileChooser = new SaveFileDialog())
{
taxpayerFileChooser.Filter = "All text files|*.txt";
if (DialogResult.OK == taxpayerFileChooser.ShowDialog())
{
taxpayerFile = taxpayerFileChooser.FileName;
}
}
if (!string.IsNullOrEmpty(taxpayerFile))
{
using (StreamWriter fileWriter = new StreamWriter(taxpayerFile, true))
{
foreach (Taxpayer tp in Taxpayers)
{
taxpayerLine = tp.Name + "," +
tp.Salary.ToString() + "," +
tp.InvestmentIncome.ToString() + "," +
(tp.InvestmentIncome + tp.Salary).ToString() + "," +
tp.GetRate().ToString() + "," +
tp.GetTax().ToString();
fileWriter.WriteLine(taxpayerLine);
}
}
myFile = new FileInfo(taxpayerFile);
myFileName = myFile.Name;
MessageBox.Show("Data Saved to " + myFileName);
}
else
{
MessageBox.Show("Data not saved");
}
}
The using statement explicit calls the Dispose() method of disposable objects after the block execution. http://msdn.microsoft.com/en-us/library/yh598w02.aspx

Adding DateTime to filename during rename

I have found lots of examples of people creating new files and adding the current Datetime then the file extension but what I want to do is look to see if a file currently exists and if it does simply add the current DateTime to the file name but I can't figure out how to maintain the file extension. My current code so far:
public class FileUploadHelper
{
private CoreSiteContext db = new CoreSiteContext();
public Int64 UploadSiteImage(string ContainerName, string NewFileName, HttpPostedFile UploadedFile)
{
string SavePath = #"F:\FFInfoImages\" + ContainerName + #"\";
if (System.IO.File.Exists(SavePath + NewFileName))
{
System.IO.File.Move(SavePath + NewFileName, SavePath + NewFileName + DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss"));
UploadedFile.SaveAs(SavePath + NewFileName);
}
else
{
UploadedFile.SaveAs(SavePath + NewFileName);
}
using (db)
{
File NewFile = new File()
{
FileName = NewFileName,
ContentType = UploadedFile.ContentType
};
db.Files.Add(NewFile);
db.SaveChanges();
return NewFile.ID;
}
}
}
Appears as if the NewFileName string variable does not get passed in with the filename extension, otherwise most of this should work. Why not get the extension from UploadedFile?
string strNewPath = SavePath + NewFileName + Path.GetExtension(UploadedFile.FileName);
if (System.IO.File.Exists(strNewPath)) {
System.IO.File.Move(strNewPath, SavePath + NewFileName + DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss") + Path.GetExtension(UploadedFile.FileName));
UploadedFile.SaveAs(strNewPath);
}
else {
UploadedFile.SaveAs(strNewPath);
}
using (db) {
File NewFile = new File() {
FileName = NewFileName + Path.GetExtension(UploadedFile.FileName),
ContentType = UploadedFile.ContentType
};
db.Files.Add(NewFile);
db.SaveChanges();
return NewFile.ID;
}
.NET has built-in methods for safely extracting the different portions of a file name (the file's name and it's extension, respectively). Path exists in the System.IO namespace.
Path.GetExtension
Path.GetFileNameWithoutExtension
Assuming NewFileName is something like myfilename.txt, you could use it like this (untested):
if (File.Exists(SavePath + NewFileName))
{
var name = Path.GetFileNameWithoutExtension(NewFileName);
var ext = Path.GetExtension(NewFileName);
File.Move(SavePath + NewFileName,
SavePath + name + DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss") + ext);
}
UploadedFile.SaveAs(SavePath + NewFileName);
The following method totally solves your problem
System.IO.Path.GetExtension("Path");
You'd better get the current file name without extension first using System.IO.Path.GetFileNameWithoutExtension("Path") then add the Date Time and then add up the extension anyway.
you can use Path.GetExtension() method to identify the file extension.
Try This:
String strExtension=IO.Path.GetExtension(SavePath + NewFileName);
if (System.IO.File.Exists(SavePath + NewFileName))
{
System.IO.File.Move(SavePath + NewFileName, SavePath + NewFileName + DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss")+strExtension);
UploadedFile.SaveAs(SavePath + NewFileName);
}
else
{
UploadedFile.SaveAs(SavePath + NewFileName);
}

How to specify the Streamwriter path location

I wanted to write a text to file using StreamWriter.But Filename should be current date name.
here is my coding.Can somebody tell me how to specify the file creation path?
Code Edit :
In here i wanted to create a .txt file but in here file not created.
public void WriteToFile( string name, string source, int dest, string messageIn, string operatorNew)
{
string directory = ResolveUrl("~/DesktopModules/SMSFunction/SMSText");
string filename = String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now,name);
string path = Path.Combine(directory, filename);
if (!File.Exists(filename))
{
using (StreamWriter str = File.CreateText(path))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
else if (File.Exists(filename))
{
using (var str = new StreamWriter(filename))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
you need to make following changes
1.Replace ResolveUrl with Server.MapPath
string directory = Server.MapPath("~/DesktopModules/SMSFunction/SMSText");
2.Add the file extension .txt as shown below
string filename = String.Format("{0:yyyy-MM-dd}__{1}.txt", DateTime.Now,name);
3.when you are checking whether file exists or not provide the path of the file , instead of filename
File.Exists(path);
4.under the else if block , here also provide the path , instead of filename
var str = new StreamWriter(path));
putting all together the code looks like,
string directory = Server.MapPath("~/DesktopModules/SMSFunction/SMSText");
string filename = String.Format("{0:yyyy-MM-dd}__{1}.txt", DateTime.Now, name);
string path = Path.Combine(directory, filename);
if (!File.Exists(path))
{
using (StreamWriter str = File.CreateText(path))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
else if (File.Exists(path))
{
using (var str = new StreamWriter(path))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
File.Create returns FileStream, and you need StreamWriter. You'll have to use its constructor that accepts Stream:
using (var str = new StreamWriter(File.CreateText(path)))
Simplify, use FileStream to create or overwrite your file (see below) depending on your neeeds you might want to change the FileMode to be something else (Append ?)
public void WriteToFile(string name, string source, int dest, string messageIn, string operatorNew)
{
string directory = ResolveUrl("~/DesktopModules/SMSFunction/SMSText");
string filename = String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now,name);
string path = Path.Combine(directory, filename);
using (FileStream fs = new FileStream(path, FileMode.Create))
{
using (StreamWriter str = new StreamWriter(fs))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
}
Let's say your console app project name is DataPrep. Now you can write in Data directory location by creating a new file namely as db.json
string filePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, #"..\..\..\")) + #"Data\db.json";
if (!File.Exists(filePath))
{
using (StreamWriter _streamWriter = File.CreateText(filePath))
{
_streamWriter.Write(resultAll);
_streamWriter.Flush();
}
}
else if (File.Exists(filePath))
{
using (var _streamWriter = new StreamWriter(filePath))
{
_streamWriter.Write(resultAll);
_streamWriter.Flush();
}
}

Categories