C# checkBox_CheckedChanged Referencing in different files - c#

Requirement: I have a windows application written in C# and I'm trying to add a checkbox to it where if it is checked, than the files from the search will be copied into subdirectories based on zip code.
Problem: When I reference addzipdir_checkBox.Equals(true) from MainForm.cs on a different page SearchProcess.cs I get the error: "addzipdir_checkBox does not exist in the current context". What is the proper way to reference the checkBox_CheckedChanged occurence?
Here's the code on MainForm.cs:
private void addzipdir_checkBox_CheckedChanged(object sender, EventArgs e)
{
if (addzipdir_checkBox.Equals(true))
{
Log("Organize files by zip code.");
}
if (addzipdir_checkBox.Equals(false))
{
Log("Don't Organize files by zip code.");
}
}
Here's the code on SearchProcess.cs generating an error:
if (addzipdir_checkBox.Equals(true))
{
// adds the given lead's agentid and zip code to the targetpath string
string targetzipdir = m_sc.get_TargetPath() + "\\" + AgentID + "\\" + ZIP;
// If the given lead's zip code subdirectory doesn't exist, create it.
if (!Directory.Exists(targetzipdir))
{
Directory.CreateDirectory(targetzipdir);
}
targetFileAndPath = m_sc.get_TargetPath() + "\\" + AgentID + "\\" + ZIP + "\\" + fullFileName;
} // end if addzipdir_checkBox.Equals(true)

You need to make sure addzipdir_checkBox is public. For this, you need to use the form editor, select the addzipdir_Checkbox and change the property grid 'Modifiers' item to public or internal.
Then, you need to find a way to reference the instance of this form, something like this:
if (myForm.addzipdir_checkBox.Equals(true))
{
...
...
}

I found that if you right click a variable and click "Go To Definition" it's a lot easier to find where the variable is referenced. I right clicked another variable that was called in through the MainForm and found that they were all called through the SearchCriteria file. I had to bring the addzipdir_checkbox value referenced on the MainForm.cs file through the SearchCriteria.cs file and then call it in the SearchProcess.cs file.
Here's my code on the SearchCriteria.cs file:
public class SearchCriteria
{
private String Corp;
private String OrderNumber;
private String Campaign;
private String City;
private String State;
private String Zip;
private String SourcePath;
private String TargetPath;
private bool SearchOR;
private bool SearchAND;
private bool addzipdirectory_checkBox;
public SearchCriteria()
{
}
public SearchCriteria(String Corp,
String OrderNumber,
String Campaign,
String City,
String State,
String Zip,
String SourcePath,
String TargetPath,
bool SearchOR,
bool SearchAND,
bool addzipdirectory_checkBox)
{
this.Corp = Corp;
this.OrderNumber = OrderNumber;
this.Campaign = Campaign;
this.City = City;
this.State = State;
this.Zip = Zip;
this.SourcePath = SourcePath;
this.TargetPath = TargetPath;
this.SearchOR = SearchOR;
this.SearchAND = SearchAND;
this.addzipdirectory_checkBox = addzipdirectory_checkBox;
}
public bool get_addzipdir_checkBox()
{
return addzipdirectory_checkBox;
}
public void set_addzipdir_checkBox(bool x)
{
addzipdirectory_checkBox = x;
}
}
Here's my code on the Searchprocess.cs file:
// Copy the file if ANY of the search criteria have been met
if (found)
{
m_form.Invoke(m_form.m_DelegateAddString, new Object[] {"FOUND: Order_No: " + Order_No +
" barcode: " + barcode +
" MailerCode: " + MailerCode +
" AgentID: " + AgentID +
" City: " + City +
" State: " + State +
" ZIP: " + ZIP});
//passes values to TransferFile
TransferFile(directory, barcode, AgentID, ZIP);
}
} // end for that finds each matching record
}
// find and copy the file to the target directory string ZIP
private void TransferFile(string sourceDir, string filename, string AgentID, string ZIP)
{
string fullFileName = filename + ".pdf";
string fullFileNameAndPath = sourceDir + "\\" + fullFileName;
string targetFileAndPath;
if (m_sc.get_addzipdir_checkBox()==true)
{
// adds the given lead's agentid and zip code to the targetpath string
string targetzipdir = m_sc.get_TargetPath() + "\\" + AgentID + "\\" + ZIP;
// If the given lead's zip code subdirectory doesn't exist, create it.
if (!Directory.Exists(targetzipdir))
{
Directory.CreateDirectory(targetzipdir);
}
targetFileAndPath = m_sc.get_TargetPath() + "\\" + AgentID + "\\" + ZIP + "\\" + fullFileName;
} // end if addzipdir_checkBox.Equals(true)

Related

Saving files to a folder with a numeric system C#

I am having some trouble with my program. Is there anyway to store an array to a file but every file have a different name. For Example:
1.txt
2.txt
3.txt
4.txt
I am using Visual Studio 2019 and Coding in C#. This is some of the code im using:
string selectedsite = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
string selectedsize = this.comboBox1.GetItemText(this.comboBox2.SelectedItem);
string selectedproduct = this.comboBox1.GetItemText(this.comboBox3.SelectedItem);
string selectedproxies = this.comboBox1.GetItemText(this.comboBox4.SelectedItem);
string selectedprofiles = this.comboBox1.GetItemText(this.comboBox5.SelectedItem);
string path = "d:\\bot\\bot\\Task.txt";
string[] FileInfo = { selectedsite," ", selectedsize, " ", selectedproduct, " ", selectedproxies, " ", selectedprofiles };
You can use File.WriteAllLines method to store an array to a file and every file have a different name.
Here is a code example you can refer to.
int count = 1;
string path =#"C:\Users\Desktop\Test\{0}.txt";
private void button2_Click(object sender, EventArgs e)
{
while (System.IO.File.Exists(string.Format(#"C:\Users\Desktop\Test\{0}.txt", count)))
{
count++;
}
string selectedsite = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
string selectedsize = this.comboBox1.GetItemText(this.comboBox2.SelectedItem);
string selectedproduct = this.comboBox1.GetItemText(this.comboBox3.SelectedItem);
string selectedproxies = this.comboBox1.GetItemText(this.comboBox4.SelectedItem);
string selectedprofiles = this.comboBox1.GetItemText(this.comboBox5.SelectedItem);
string[] FileInfo = { selectedsite, " ", selectedsize, " ", selectedproduct, " ", selectedproxies, " ", selectedprofiles };
var newFileName = string.Format(#"C:\Users\Desktop\Test\{0}.txt", count);
count++;
System.IO.File.WriteAllLines(newFileName, FileInfo);
}

How do I properly auto append to filename if file exist

Here is what I have tried, please note that lblImageAlt.Text property has been set to 'Images/'
string ImgPath1 = lblImageAlt1.Text.ToString();
string ImgPath2 = lblImageAlt2.Text.ToString();
string ImgPath3 = lblImageAlt3.Text.ToString();
string filename1 = "";
string filename2 = "";
string filename3 = "";
if (fileuploadimages1.HasFile)
{
if (File.Exists(Server.MapPath(ImgPath1 + filename1)))
{
string extension = Path.GetExtension(filename1);
string name = Path.GetFileNameWithoutExtension(filename1);
int fileMatchCount = 1;
while (File.Exists(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension)))
fileMatchCount++;
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension));
}
else
{
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + filename1));
}
}
else
{
filename1 = "noImage.jpg";
}
but the same image does not get a number appended to it. What am I doing wrong here?
Path.GetFileName returns the whole filename with the extension.
Thus your code is checking if a file exists with a name like this:
image.jpg1
You should change the code to split the filename in two parts, the base filename and the extension, then check if the filename exists and then rebuild the filename from its parts adding the increment number until you find a non existant filename
// Extract just the filename from the posted file removing the path part (image.jpg)
filename1 = Path.GetFileName(fileuploadimages1.PostedFile.FileName);
baseFile = Path.GetFileNameWithoutExtension(fileuploadimages1.PostedFile.FileName);
extension = Path.GetExtension(fileuploadimages1.PostedFile.FileName);
int fileMatchCount = 1;
// Check if a file with the given name exists in the Images1 subfolder of the root folder of your site
while(File.Exists(Server.MapPath(Path.Combine(ImgPath1, filename1)))
{
// The given file exists already, so we now need to build
// a different (but related) filename using a counter....
// This will create a filename like 'image(001).jpg'
// and then we will restart the loop
fileName1 = string.Format("{0}({1:D3}){2}", baseFile, fileMatchCount, extension);
// ... but first increment the counter in case even the new name exists
fileMatchCount++;
}
// We exit the loop with a name that should not exists in the destination folder
fileuploadimages1.SaveAs(Server.MapPath(Path.Combine(ImgPath1, filename1));
You're not actually modifying filename1. You're checking if it ends in a (0), (1), etc. and incrementing your index, but never actually modifying the variable.
Try using
if(File.Exists(Server.MapPath(ImgPath1 + filename1)))
{
string extension = Path.GetExtension(filename1);
string name = Path.GetFileNameWithoutExtension(filename1);
int fileMatchCount = 1;
while(File.Exists(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension)))
fileMatchCount++;
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension));
}
else
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + filename1));

Could not get XmlDocument.Save to save into a specific file located in a specific location

Strange, I can't get ASP.Net project (using C# mode) to log result into my D:\Web.log file and also no exception was thrown.
Is there something wrong with my simple code?
private static XmlDocument _doc = new XmlDocument();
private static string LogFileName = "D:\\Web.log";
static void LogToFile(string WebAddress, string IPAddress, string Title)
{
if (File.Exists(#"" + LogFileName + ""))
_doc.Load(#"" + LogFileName + "");
else
{
var root = _doc.CreateElement("Web");
_doc.AppendChild(root);
}
try
{
var el = (XmlElement)_doc.DocumentElement.AppendChild(_doc.CreateElement("Web"));
el.SetAttribute("Title", Title);
el.AppendChild(_doc.CreateElement("WebAddress")).InnerText = WebAddress;
el.AppendChild(_doc.CreateElement("IPAddress")).InnerText = IPAddress;
_doc.Save(#"" + LogFileName + "");
}
catch (Exception ex)
{
}
}
By removing the file D:\Web.log that I created, it is now able to append the file.
Remove the #"" and leading "" from all instances of #"" + LogFileName + "".
They are not needed as you have already escaped the variable LogFileName.

saving text to a file

I have a question that's driving me nuts. I have a program that saves error messages to a string in an object, then writes the string to a file in the unloadContent() thing. For some reason I keep getting Not Supported Exceptions. Here is the code in unloadContent():
if (debug.getContent().Length > 0)
{
saveErrors save = new saveErrors();
if (Directory.Exists(System.IO.Directory.GetCurrentDirectory() + "\\Errors")) ;
Directory.CreateDirectory(System.IO.Directory.GetCurrentDirectory() + "\\Errors");
save.save(System.IO.Directory.GetCurrentDirectory().ToString() + "\\Errors\\errorLog_" + (System.DateTime.Now.ToString().Replace("/", "_")).Replace(" ","") + ".txt");
}
and here's the code in class save errors:
public class saveErrors
{
private string mess = debug.getContent();
public void save(string fileName)
{
Debug.WriteLine(fileName);
using (StreamWriter sw = new StreamWriter(fileName))
{
sw.Write(mess);
sw.Close();
}
}
}
I'm still a bit new to C#, so any help would be greatly appreciated!
Thanks!
Try this:
[Test]
public void SaveTextTest()
{
string relativePath=#"Errors\errorLog_";
string directoryPath = System.IO.Path.Combine( System.IO.Directory.GetCurrentDirectory() , relativePath);
var directoryInfo = new DirectoryInfo(directoryPath);
if(directoryInfo.Exists==false)
directoryInfo.Create();
string fileName = System.DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss") + ".txt";
string path = System.IO.Path.Combine(directoryPath, fileName);
string textToSave = "This will be saved";
File.WriteAllText(path, textToSave);
}
To get the DateTime.ToString() in the desired format you can pass a formatstring
save.save(System.IO.Directory.GetCurrentDirectory().ToString() + "\\Errors\\errorLog_" + (System.DateTime.Now.ToString().Replace("/", "_")).Replace(" ", "").Replace(":", "") + ".txt");
Change it to that. You need a .Replace(":", "") because : Is included in the date part of the code, but is invalid in a file name, so you must either remove it or replace it with something else.
As an alternative you could format the date as so:
save.save(System.IO.Directory.GetCurrentDirectory().ToString() + "\\Errors\\errorLog_" + System.DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss"));

Change filename on file upload in .net (asp)

How to change file name on upload ?
I have such code :
<%# WebHandler Language="C#" Class="Upload" %>
using System;
using System.Web;
using System.IO;
public class Upload : IHttpHandler {
public void ProcessRequest(HttpContext context) {
HttpPostedFile oFile = context.Request.Files["Filedata"];
string newFileName1 = HttpContext.Current.Server.MapPath(#context.Request["orderID"]);
string newFileName2 = HttpContext.Current.Server.MapPath(#context.Request["productCombinationString"]);
string newName;
if(newFileName2 != "" && newFileName2 != null && newFileName2 != "<!--#Ecom:productCombinationString-->") {
newName = newFileName1 + newFileName2 + oFile.ContentType;
} else {
newName = newFileName1 + oFile.ContentType;
}
string sDirectory = HttpContext.Current.Server.MapPath(#context.Request["folder"]);
oFile.SaveAs(sDirectory + "/" + oFile.FileName);
if (!Directory.Exists(sDirectory)) Directory.CreateDirectory(sDirectory);
context.Response.Write("1");
}
public bool IsReusable {
get { return false; }
}
}
And if i change oFile.Filename to newName it does not work ... what is the problem ? :)
Thank you
You can pass your Custom File Name along with Directory to SaveAs Method
oFile.SaveAs(sDirectory + "/" + "abc");
try:
// Get the extension of the uploaded file.
string fileName = Server.HtmlEncode(FileUpload1.FileName);
string extension = System.IO.Path.GetExtension(fileName);
string newName;
if(newFileName2 != "" && newFileName2 != null && newFileName2 != "<!--#Ecom:productCombinationString-->") {
newName = newFileName1 + newFileName2 + extension ;
} else {
newName = newFileName1 + extension ;
}
oFile.SaveAs(sDirectory + "/" + newName );
I haven't tried this code but I do want to point out two things of from the original code:
The first is this order of operations:
oFile.SaveAs(sDirectory + "/" + oFile.FileName);
if (!Directory.Exists(sDirectory)) Directory.CreateDirectory(sDirectory);
I believe it should be this instead. In the above sequence, there is a potential edge case of saving into a non-existing folder. This ensures that the folder is created:
if (!Directory.Exists(sDirectory))
{
Directory.CreateDirectory(sDirectory);
}
oFile.SaveAs(sDirectory + "/" + oFile.FileName);
The other thing is that you might be running into issues with / as the path separator. I think it should be much safer to do something like:
var saveLocation = Path.Combine(sDirectory, oFile.FileName);
oFile.SaveAs(saveLocation);
I hope this helps!
Here is an example i used when saving an image look at the save as section
////saving file in the physical folder;
FileUpload FileUpload1 = file_Image;
string virtualFolder = "~/Resourceimages/";
string physicalFolder = HostingEnvironment.MapPath(virtualFolder);
string PhotoName = ((string)Session["UserName"] + (string)Session["UserSurname"]);
FileUpload1.SaveAs(physicalFolder + PhotoName + FileUpload1.FileName);
string location = virtualFolder + PhotoName + FileUpload1.FileName;
webservice.UpdateResourceImage((int)Session["UserID"], location);
lbl_Result.Text = "Your file " + FileUpload1.FileName + " has been uploaded.";
Image1.Visible = true;
Image1.ImageUrl = location;
string uploadFolder = Request.PhysicalApplicationPath + "UploadFile\\";
if (FileUpload1.HasFile)
{
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(uploadFolder + "Test"+ extension);
Label1.Text = "File uploaded successfully as: " + "Test"+ extension;
}
else
{
Label1.Text = "First select a file.";
}
private string UpdateFilename(string filename)
{
try
{
filename = Server.HtmlEncode(FUJD.FileName);
string extension = System.IO.Path.GetExtension(filename);
filename = filename.Replace(extension, "");
return filename + '-' + DateTime.Now.ToString("yyyyMMddHHmmss") + extension;
}
catch (Exception ex)
{
throw ex;
}
}

Categories

Resources