Value of a variable is not updating - c#

I am currently working on a project that sweeps a mailbox for attachments and when one is found it is placed in the user's directory. My problem is that when I check if the file exist in the path, I alter the attachment's name and add a counter and time stamp, that way it is not over written. However, when it goes into the condition and changes the file name it never updates the path variable to include the right value of the Clean name variable.
string timeProcessed = DateTime.Now.ToString();
byte[] bytefiles = attachment.ContentBytes;
string cleanName = MakeCleanName(userEmail.Subject, attachment.Name);
string path = employeeStarPath + "\\" + cleanName;
// updated this in order to prevent images with the same name from overwritting eachother.
if (File.Exists(path))
{
cleanName = Path.GetFileNameWithoutExtension(attachment.Name).ToString()+"(" + counter + ")" + "-(Recieved - " + timeProcessed.Replace(":",".").Replace("/",".") + " )"+ Path.GetExtension(attachment.Name); << this value is not updated in the path variable.
}
Now I am aware I can update the path var by calling path = employeeStarPath + "\\" + cleanName; again but I feel that this makes my code a bit confusing.

I might not understood your question but can you just call the line "string path = employeeStarPath + "\" + cleanName;" at the end instead before the if?
string timeProcessed = DateTime.Now.ToString();
byte[] bytefiles = attachment.ContentBytes;
string cleanName = MakeCleanName(userEmail.Subject, attachment.Name);
// updated this in order to prevent images with the same name from overwritting eachother.
if (File.Exists(path))
{
cleanName = Path.GetFileNameWithoutExtension(attachment.Name).ToString()+"(" + counter + ")" + "-(Recieved - " + timeProcessed.Replace(":",".").Replace("/",".") + " )"+ Path.GetExtension(attachment.Name); << this value is not updated in the path variable.
}
string path = employeeStarPath + "\\" + cleanName;

Related

Increment file name by 1 if the file exists in c#

I am trying to increment the filename (e.g., "file1.csv", "file2.csv", etc.), each time a new file is generated. I followed this thread Increment the file name if the file already exists in c# but the solution is not useful for my case. What I want to do is check if the file exists in the first place and if it does write in it. If it doesn't create one and write. The problem is that if the file exists but it's from another user, I want the system to increment the file number and not write to the same file just because it exists. What I have so far:
public void saveFile()
{
int count = 0;
string title = "TimeStamp,Name,Trial,Time_spent-dist,Time_spent_tar\n";
string output = System.DateTime.Now.ToString("mm_ss_ffff") + "," +
currentScene.name.ToString() + "," +
trialNum.ToString() + "," +
timerDistractor.ToString() + "," +
timerTarget.ToString();
string fname = "User_" + count + ".csv";
string path = Path.Combine(Application.persistentDataPath, fname);
if (File.Exists(path))
{
File.AppendAllText(path, "\n" + output);
}
else
{
StreamWriter writer = new StreamWriter(path);
writer.WriteLine(title + "\n" + output);
writer.Close();
}
}
Any pointers?

Writing to docx using xceed.words.net.docx, works when run in VS, writes a line per page when run as built exe

I've been using this for a while and it's always worked fine. The project writes to a docx log file as it runs. I recently made a modification to the path it writes the log to for someone else to use. Since then, when I run it as a built exe it writes one line per page. But when I attempt to fix the problem, I can't recreate it running it in VS. From there it works like it always had.
Any ideas? A direction someone can point me toward?
public static void WritetoLogFile(string logUpdate)
{
DateTime now = DateTime.Now;
string logDate = now.ToString("MM-dd");
string folderNameDate = now.ToString("MM_dd_yyyy");
string folderName = folderNameDate + "_Logs";
string stateFolder = " ";
System.IO.Directory.CreateDirectory(Crawlspace.networkSharePath + "//" + folderName);
string logName = logDate + "_" + Crawlspace.browser + "_" + Crawlspace.computerName + "_" + Crawlspace.SuiteTable + ".docx";
Crawlspace.LogFileName = logName;
System.IO.Directory.CreateDirectory(Crawlspace.networkSharePath + folderName + "//" + stateFolder);
Crawlspace.LogFile = Crawlspace.networkSharePath + folderName + "//" + stateFolder + "//" + logName;
if (System.IO.File.Exists(Crawlspace.LogFile))
{
using (DocX document = DocX.Load(Crawlspace.LogFile))
{
Paragraph par1 = document.InsertParagraph();
par1.Append(logUpdate);
par1.Font("Courier New");
par1.FontSize(8);
document.Save();
}
}
else
{
using (DocX document = DocX.Create(Crawlspace.LogFile))
{
Paragraph par1 = document.InsertParagraph();
par1.Append(logUpdate);
par1.Font("Courier New");
par1.FontSize(8);
document.Save();
}
}
}
RESOLVED:
I checked the xceed.words.net.docx dll in the nuget manager and found there was an update. Updated to the latest and modified my using statements to reflect the update and it's now working....
using Image = Xceed.Document.NET.Image;
using Paragraph = Xceed.Document.NET.Paragraph;
using Picture = Xceed.Document.NET.Picture;

Exclude Sub Folder Within Directory C#

I wanted to exclude a folder within directory when copying the directory to other location could anyone please help me out ?
string logZipTarget = "PangaeaLogs_Fail_" + currentLocation + "_" + classID + "_" + tracer + "_" +
DateTime.Now.ToString("ddMMMyyyy-HH-mm-ss", System.Globalization.CultureInfo.InvariantCulture) + ".zip";
string buildTypeFile = #"C:\build.typ";
string journalFile = #"C:\Mavis\" + tracer + ".ejl";
string logsPath = #"C:\Pangaea\PangaeaFinancialLogs\"; //Path to copy directory to
File.Copy(buildTypeFile, logsPath + "build.typ", true);
File.Copy(journalFile, logsPath + tracer + ".ejl", true);
Helper.DirectoryCopy(#"C:\Program Files\NCR\Pangaea\", logsPath, true);
executor.ZipFolder(logsPath, logZipTarget);
Inside this location C:\Pangaea\PangaeaFinancialLogs\ApplicationData i wanted to remove this folder SessionBackup but what is happening is it is copyin all the folders inside this location
string logsPath = #"C:\Pangaea\PangaeaFinancialLogs\";
From the bit of code provided in your comment I can only assume which classes your using. If I'm correct this should do the trick:
DirectoryInfo currentFolder = new DirectoryInfo("");
String NameOfFolderNotToInclude = "";
if(currentFolder.Name != NameOfFolderNotToInclude)
{
File.Copy(newPath, newPath.Replace(#"\\xxx\yyy", #"C:\bbb"), true);
}
Always keep in mind that equals (MSDN) if not overidden will always compare the actual objects for equality. In your case a string will never be the same as a DirectoryInfo and thus not be equal even if the DirectoryInfo is pointing at the location the string describes.

c# executed even when in false loop

I am trying to use a basic if else case, but the if is executed no matter what.
This is the code found in the backend, on the aspx.cs file.
if (1==2)
{
// 22/09/2014 12:00:00 AM for en
//format date for submit
Dateformatted = this.DateField.Value.ToString();
DateSplit = Dateformatted.Split('/');
yearAt0 = DateSplit[2].Split(' ');
Datetosubmit = yearAt0[0] + "/" + DateSplit[1] + "/" + DateSplit[0] + " 00:00:00";
}
else
{
// 2014-09-22 00:00:00 for fra
//format date for submit
Dateformatted = this.DateField.Value.ToString();
DateSplit = Dateformatted.Split('-');
dayAt0 = DateSplit[2].Split(' ');
Datetosubmit = DateSplit[0] + "/" + DateSplit[1] + "/" + dayAt0[0] + " 00:00:00";
}
This is the error I get (line 1209 is red):
System.IndexOutOfRangeException: Index was outside the bounds of the array.
Line 1207: string Dateformatted = this.DateFieldEdit.Value.ToString();
Line 1208: string[] DateSplit = Dateformatted.Split('/');
Line 1209: string[] yearAt0 = DateSplit[2].Split(' ');
Line 1210: string Datetosubmit = yearAt0[0] + "/" + DateSplit[1] + "/" + DateSplit[0] + " 00:00:00";
Line 1211:
This clearly indicates that the code inside the false part of the if statement was executed. Is there a reason for this? How can I fix this?
Note: The if (1==2) was added to simplify the example, it is normally a parameter
You can see this effect if your binaries and your PDB files are out of sync. If you are using the updated PDBs, but the old binaries, that would definitely explain this scenario.
The easiest way to fix this to to completely clean and rebuild everything. Deleting everything in your bin and obj folders for good measure. You should also restart the IIS instance you are using.

File.ReadAllText and after File.WriteAllText

My questions is, when i run this code its tell me on "File.WriteAllText" line procedure.pas is using by another program.
script = File.ReadAllText(Application.StartupPath + "\\Procedure.pas");
decryptedstring = Crypter.Decrypt(script, sSecretKey);
decryptedstring = decryptedstring.Replace("_" + Firma + "_", "_" + txtFirma.Text + "_");
decryptedstring = decryptedstring.Replace("_" + DonemNo + "_", "_" + txtDonemNo.Text + "_");
decryptedstring = decryptedstring.Replace("FIRMNR=" + Firma + " ", "FIRMNR=" + txtFirma.Text + " ");
encryptedstring = Crypter.Encrypt(decryptedstring, sSecretKey);
File.WriteAllText(Application.StartupPath + "\\Procedure.pas", encryptedstring);
It is possible that the file you are writing is opened with a shared lock that allows reading data by other processes but does not allow writing. So when you are opening the file for write, it fails with the exception although the file was opened by another process the whole time.
See FileShare enumeration for details on this.

Categories