C# str.Replace only replaces first character - c#

This is my code, I know it isn't optimal, but it works for me.
private void textBox_title1_TextChanged(object sender, EventArgs e)
{
string title1 = textBox_title1.Text;
string currentDirectory = Directory.GetCurrentDirectory();
DateTime folderDate = DateTime.Today;
string workingFolder = folderDate.ToString("ddMMMyy");
string mailingDir = ("mailingdir\\");
string indexPage = (mailingDir + "\\" + workingFolder + "\\" + "index.html");
String appdir = Path.GetDirectoryName(Application.ExecutablePath);
String title1open = Path.Combine(appdir, mailingDir, workingFolder, "index.html");
string str = File.ReadAllText(title1open, Encoding.UTF8);
str = str.Replace("[title1]", title1);
File.WriteAllText(title1open, str);
}
However, this only saves the first character that is entered into textBox_title1

Related

string path is correct, but gives an error on .zip extract c#

Context: i have a zip file in %appdata%.lucaclient\java\java.zip but when I build the project it doesn't work.
strings:
string path = #"C:\%userprofile%\AppData\Roaming\.lucaclient";
string downloadClientPath = #"C:\%userprofile%\AppData\Roaming\.lucaclient\Client 1.8.8";
string downloadJavaPath = #"C:\%userprofile%\AppData\Roaming\.lucaclient\java";
string extractJavaPath = #"C:\%userprofile%\AppData\Roaming\.lucaclient\java\java.zip";
on click code:
private void pictureBox2_Click(object sender, EventArgs e)
{
if(firstLaunch == true)
{
ZipFile.ExtractToDirectory(extractJavaPath, downloadJavaPath);
}
}
error after build, but path is correct
you need to fill the userprofile path proberly.
try this function:
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Roaming\.lucaclient";
string downloadClientPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Roaming\.lucaclient\Client 1.8.8";
string downloadJavaPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Roaming\.lucaclient\java";
string extractJavaPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Roaming\.lucaclient\java\java.zip";

Restore sqlite database in c#

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

Command to copy a file to another, user-chosen directory?

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);
}

C# fail to create file in directory if has other file

Can someone help me, I just learning C# for about 2 month, I have this problem,
i'm building a class for filter data from temp file and create the result in new txt file inside directory, if directory is empty nor at the same date, it build perfectly, and if there another file at same date it should create with increase the last number at lastname.
My problem when I run code, it is not creating if the directory has files with the same dates, then the result should be something like this:
C:\result_2014051301.txt
C:\result_2014051401.txt
C:\result_2014051402.txt <-- Failed, it is not ..2014051401.txt
class Entity2
{
public Entity2()
{
string fileTemp = "DEFAULT.temp";
string indexD = Properties.Settings.Default.ChIndex2D;
string indexC = Properties.Settings.Default.ChIndex2C;
string indexS = Properties.Settings.Default.ChIndex2S;
string tempPath = AppDomain.CurrentDomain.BaseDirectory;
string targetPath = Properties.Settings.Default.ExtractALL_DIR;
string SourceFile = Path.Combine(tempPath, fileTemp);
string tempFileX = Path.GetTempFileName();
if (!System.IO.Directory.Exists(targetPath))
{
System.Windows.Forms.MessageBox.Show("Error missing .temp", "Message Box");
}
else
{
string ext = ".txt";
int sequence = 0;
DateTime dateFileName = DateTime.Today;
string discode = Properties.Settings.Default.ChannelID_2;
string filename = discode + "_" + dateFileName.ToString("yyyyMMdd");
string pathX = Properties.Settings.Default.ExtractALL_DIR + #"/Channel2";
if (!Directory.Exists(pathX))
{
Directory.CreateDirectory(pathX);
}
string[] files = Directory.GetFiles(pathX, filename + "*.txt", SearchOption.TopDirectoryOnly);
if (files.Length > 0)
{
Array.Sort(files);
string lastFilename = files[files.Length - 1];
sequence = Int32.Parse(lastFilename.Substring(0, lastFilename.Length - 4).Replace(pathX + filename, ""));
}
sequence++;
string newFileName = filename + sequence.ToString().PadLeft(2, '0') + ext;
string DestFile = Path.Combine(pathX, newFileName);
using (var ab = new StreamReader(SourceFile))
using (var cd = new StreamWriter(DestFile))
{
string lineX;
while ((lineX = ab.ReadLine()) != null)
{
if (lineX.LastIndexOf("100", 3) != -1 || lineX.LastIndexOf("MGR", 15) != -1 || lineX.LastIndexOf(indexC, 15) != -1)
{
lineX = lineX.Replace(indexD, "");
lineX = lineX.Replace("DEFAULT", discode);
if (lineX.LastIndexOf("800", 3) != -1)
{
lineX = lineX.Replace(indexS, "");
}
cd.WriteLine(lineX);
}
}
}
}
}
}
This piece is not functioning correctly:
Int32.Parse(lastFilename.Substring(0, lastFilename.Length - 4).Replace(pathX + filename, ""));
pathX + filename is C:\folderfile.txt not C:\folder\file.txt.
You either need to add the \ or call Path.Join.
That will cause the Parse operation to fail since it tries to consume the who string (minus the extension).

asp.net textbox and dropdownlist loses value on postback

i have a 4 textboxes on my webpage, one of which is populated using a javascript calender control...the problem is that all of these textboxes lose their value after a postback (clicking an asp.net button control). the textboxes are not readonly so i cant figure out why this is so...please help...and thanks
protected void Page_Load(object sender, EventArgs e)
{
BindProdTopDetails();
BindProdTable();
// BindProdComment();
}
protected void BtnProdUpdate_Click(object sender, EventArgs e)
{
//saveProdDetails();
bool success = saveProdDetails();
if (success)
{
string strScript96 = "<script language=JavaScript>";
strScript96 += "javascript:alert('Update Successful');";
strScript96 += "</script>";
if (!ClientScript.IsStartupScriptRegistered("clientScript"))
ClientScript.RegisterClientScriptBlock(this.GetType(), clientScript", strScript96);
}
}
public bool saveProdDetails()
{
string prodLine = DDProdLine.SelectedValue;
string stock1 = DDMaterial.SelectedValue;
string stock2 = TextBoxMaterial.Text.Trim().ToString();
string supplier = TextBoxSupplier.Text.Trim().ToString();
string billet = RBBillet.SelectedValue;
string matTime1 = TextBoxMatTime.Text.Trim().ToString();
string matTime2 = DDMatTime.SelectedValue;
string prodTime1 = TextBoxProdTime.Text.Trim().ToString();
string prodTime2 = DDProdTime.SelectedValue;
string shipTime1 = TextBoxShipTime.Text.Trim().ToString();
string shipTime2 = DDShipTime.SelectedValue;
CultureInfo cultureInfo = CultureInfo.CurrentCulture;
string format = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString();
string cmr = cmrDue.Value.ToString();
string kc = kcDue.Value.ToString();
string x = cmr.Substring(3, 2);
string y = cmr.Substring(0, 2);
string z = cmr.Substring(6, 4);
string x1 = kc.Substring(3, 2);
string y1 = kc.Substring(0, 2);
string z1 = kc.Substring(6, 4);
string finalCmr = x + "/" + y + "/" + z;
string finalKC = x1 + "/" + y1 + "/" + z1;
DateTime dt = DateTime.ParseExact(finalCmr, format, cultureInfo);
DateTime cr = DateTime.ParseExact(finalKC, format, cultureInfo);
string custDate = dt.ToString("dd/mm/yyyy");
string kcDate = cr.ToString("dd/mm/yyyy");
string id = Request.QueryString["id"];
bool success = true;
TextBoxProdComment1.Text = stock2 + "," + supplier + matTime1 + "," + prodTime1 + "," + shipTime1 + "," + custDate
+ "," + kcDate;
try
{
success = CRTopButtons.SaveProdTable(id, prodLine, stock1, supplier, billet, matTime1, matTime2, prodTime1,
prodTime2, shipTime1, shipTime2, custDate, kcDate);
}
catch (Exception e)
{
System.Diagnostics.Trace.Write(e.StackTrace);
}
return success;
}
I doubt you are assigning/clearing textbox value in page load event...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TextBox1.Text = "";
}
}
you need to put condition if (!Page.IsPostBack) before doing so
Update with your sample code, agree about the IsPostBack flag.
if (!IsPostBack)
{
BindProdTopDetails();
BindProdTable();
// BindProdComment();
}

Categories