Replacing databases from previous to new one - c#

How can I replace my new database file to my previous database file?
My previous database is inside the folder :
string filepath = Application.persistentDataPath + "/" + "Martyr.db";
My app code:
string filePath = Application.persistentDataPath + "/" + "Martyr.db";
string disPath;
if (!File.Exists(filePath))
{
disPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Martyr.db");
WWW loadDB;
#if UNITY_ANDROID
{
loadDB = new WWW(disPath);
}
#if UNITY_EDITOR
{
loadDB = new WWW("file://" + Application.streamingAssetsPath + "/Martyr.db");
}
#else
{loadDB=new WWW(dispath);}
#endif
#endif
while (!loadDB.isDone)
{
}
File.WriteAllBytes(filePath, loadDB.bytes);
}

You can simply delete your old Databasefile and write a new one.
string filePath = Application.persistentDataPath + "/" + "Martyr.db";
string disPath;
if (File.Exists(filePath)) {
File.Delete(filePath);
}
disPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Martyr.db");
WWW loadDB;
#if UNITY_ANDROID
{
loadDB = new WWW(disPath);
}
#if UNITY_EDITOR
{
loadDB = new WWW("file://" + Application.streamingAssetsPath + "/Martyr.db");
}
#else
{loadDB=new WWW(dispath);}
#endif
#endif
while (!loadDB.isDone) {
}
File.WriteAllBytes(filePath, loadDB.bytes);

Related

JSоn file is not read

I do localization in my game, and I write words in different languages into a JSon file. Everything works in Unity Editor, but on android it throws an exception Cannot find file!
public void LoadLocalizedText(string langName)
{
#if UNITY_ANDROID && !UNITY_EDITOR
string path ="jar:file://" + Application.streamingAssetsPath + "/Languages/" + langName + ".json";
#else
string path = Application.streamingAssetsPath + "/Languages/" + langName + ".json";
#endif
if (File.Exists(path))
{
if (File.Exists(path))
{
string dataAsJson;
#if UNITY_ANDROID && !UNITY_EDITOR
WWW reader = new WWW(path);
UnityWebRequest unityWebRequest = new UnityWebRequest(path);
while (!reader.isDone) { }
dataAsJson = reader.text;
#else
dataAsJson = File.ReadAllText(path);
#endif
LocalizationData loadedData = JsonUtility.FromJson<LocalizationData>(dataAsJson);
localizedText = new Dictionary<string, string>();
for (int i = 0; i < loadedData.items.Length; i++)
{
localizedText.Add(loadedData.items[i].key, loadedData.items[i].value);
}
currentLanguage = langName;
isReady = true;
OnLanguageChanged?.Invoke();
}
else
{
throw new Exception("Cannot find file!");
}
}
You dont need to add "jar:file//" on android for streaming assets path. Also, if you on android, you'll not pass your File.Exists(pass) checks. Here is the working exapmple.

The best and right way to close StreamWriter and StreamReader

I have been trying to organize a code that it is a mess! The first and my biggest problem at this point is that one of my StreamWriters or StreamReader is being left open. Using this link, I am trying to organize my code. But my problem is that I am not sure where should I close it:
My code is:
public static void ProcessFile(string[] ProcessFile, int id_customer, string directoryinprocess)
{
StreamWriter Writer = null, Writer2 = null, Writer3 = null;
foreach (string filename in ProcessFile)
{
// Used for the output name of the file
var dir = Path.GetDirectoryName(filename);
var fileName = Path.GetFileNameWithoutExtension(filename);
var ext = Path.GetExtension(filename);
var folderbefore = Path.GetFullPath(Path.Combine(dir, #"..\"));
int rowCount = 0;
string path_body_out = "";
string outputname = folderbefore + "output_temp\\" + fileName;
if (filename.Contains("RO_"))
{
Writer = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext) { AutoFlush = true };
Writer2 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_body_out" + ext) { AutoFlush = true };
path_body_out = dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext;
} // end of if
else
{
Writer3 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_out" + ext) { AutoFlush = true };
} // end of else
using (StreamReader Reader = new StreamReader(#filename))
{
while (!Reader.EndOfStream)
{
string inputLine = string.Empty;
inputLine = Reader.ReadLine();
rowCount++;
if (filename.Contains("RO_"))
{
if (rowCount <= 4)
{
Writer.WriteLine(inputLine);
}
if (rowCount >= 5)
{
Writer2.WriteLine(inputLine);
}
}
else
{
{ Writer3.WriteLine(inputLine); }
}
} // end of the while
} // end of using Stremreader
if (path_body_out.Contains("_hd_intermediate"))
{
ManipulateHeaderFilesTypeRo(dir, path_body_out);
}
else
{ }
} // end of the foreach
string[] extensions = { "_fv", "_body", "_out" };
string[] fileEntriesout = System.IO.Directory.EnumerateFiles(directoryinprocess, "*.csv", System.IO.SearchOption.AllDirectories)
.Where(file => extensions.Any(ex => Path.GetFileNameWithoutExtension(file).EndsWith(ex)))
.ToArray();
foreach (string filenameout in fileEntriesout)
{
string destinytablename = null;
if (filenameout.Contains("_hd_intermediate_fv"))
{ destinytablename = "TBL_DATA_TYPE_RO_HEADER"; }
else if (filenameout.Contains("_body_out"))
{ destinytablename = "TBL_DATA_TYPE_RO_BODY"; }
else
{ destinytablename = "TBL_DATA_TYPE_LOAD"; }
string id_file = Get_id_file(filenameout, id_customer);
DataTable csvFileData = GetDataTabletFromCSVFile(filenameout, id_file);
InsertDataIntoSQLServerUsingSQLBulkCopy(csvFileData, destinytablename);
} // end of the foreach
//} // end of the foreach
} // end of ProcessFile
Question:
How should I close the part:
if (filename.Contains("RO_"))
{
Writer = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext) { AutoFlush = true };
Writer2 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_body_out" + ext) { AutoFlush = true };
path_body_out = dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext;
} // end of if
else
{
Writer3 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_out" + ext) { AutoFlush = true };
} // end of else
using (StreamReader Reader = new StreamReader(#filename))
{
while (!Reader.EndOfStream)
{
string inputLine = string.Empty;
inputLine = Reader.ReadLine();
rowCount++;
if (filename.Contains("RO_"))
{
if (rowCount <= 4)
{
Writer.WriteLine(inputLine);
}
if (rowCount >= 5)
{
Writer2.WriteLine(inputLine);
}
}
else
{
{ Writer3.WriteLine(inputLine); }
Should I close here?
if (filename.Contains("RO_"))
{
Writer = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext) { AutoFlush = true };
Writer2 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_body_out" + ext) { AutoFlush = true };
path_body_out = dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext;
} // end of if
else
{
Writer3 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_out" + ext) { AutoFlush = true };
} // end of else
Or here?
if (filename.Contains("RO_"))
{
if (rowCount <= 4)
{
Writer.WriteLine(inputLine);
}
if (rowCount >= 5)
{
Writer2.WriteLine(inputLine);
}
}
else
{
{ Writer3.WriteLine(inputLine); }
}
If you can't reorganize this code so that every StreamWriter instance can be wrapped in a using(), then perhaps you can do something like this:
StreamWriter Writer = null, Writer2 = null, Writer3 = null;
try
{
// your existing code
}
catch
{
// Handle
}
finally
{
if (Writer != null)
Writer.Close();
if (Writer2 != null)
Writer2.Close();
if (Writer3 != null)
Writer3.Close();
}
This ensures that no matter what error(s) happen within the try that your writers will be closed.
In my opinion, conditionally instantiating objects is a smell and you should work on having different implementations based on filename.Contains("RO_"). You could use the strategy pattern and have different file processor interface implementations, choosing the correct one based on the filename. Each implementation would only know how to write to the locations it needs. This would allow you to correctly use a using() around each writer.
Nomrally if you are using disposable objects, I would say use a using block. However, since you are conditionally instatiating disposable objects, I think the use of a try-finally block would be your best bet.
Declare disposable objects and intialize them to null outside of a try block.
Initialize the disposable objects to the instances you want inside of a try block. Take care not to change this reference anywhere inside of your try-block once you have created a disposable object.
Also inside of your try block, do everything you need to do with the disposable objects.
After your try block create a finally block (a catch block is optional, but you will need a finally block for this method to do its job.) and inside the finally block, check if the variables you declared to hold the disposable objects aren't null. and if they are not null, close them and make them null.
StreamWriter writer = null;
try {
if (condA) {
writer = new StreamWriter("filePath1");
} else if (condB) {
writer = new StreamWriter("filePath2");
} else {
writer = new StreamWriter("filePath3");
}
// do things with writer
} catch (Exception ex) {
} finally {
if (writer != null) {
writer.close();
writer = null;
}
}

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
{

How to know the extension of uploaded file before saving the file

HttpPostedFile file = context.Request.Files[j];
string fileName = file.FileName;
string fileExtension = System.IO.Path.GetExtension(filepath + file.FileName);
if (!string.IsNullOrEmpty(fileName)
{
string pathToSave_100 = HttpContext.Current.Server.MapPath(filepath) + fileName + fileExtension;
if (File.Exists(pathToSave_100))
{
File.Delete(pathToSave_100);
file.SaveAs(pathToSave_100);
}
else
{
file.SaveAs(pathToSave_100);
}
}
You can do like this:
string strFileExtension = Path.GetExtension(file.FileName);

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