Replacing hundreds of files with one simple check box check - c#

Is there a simple or a more compact way to do this with a large number of files with one check-box (checked/unchecked), i have i think few thousand lines to put inside the code and i can sort them by year, or by type:
private void CheckBox()
{
try
{
switch (checkBox.IsChecked)
{
case true:
{
const string disable_picture100 = "images/disabled/picture100.png";
const string picture100 = "images\\disabled\\picture100.png";
Records[picture100].ReplaceContents(imagesPath, disable_picture100, content.FileRoot);
const string disable_picture101 = "images/disabled/picture101.png";
const string picture101 = "images\\disabled\\picture101.png";
Records[picture101].ReplaceContents(imagesPath, disable_picture101, content.FileRoot);
const string disable_picture102 = "images/disabled/picture102.png";
const string picture102 = "images\\disabled\\picture102.png";
Records[picture102].ReplaceContents(imagesPath, disable_picture102, content.FileRoot);
UpdateImage();
}
break;
case false:
{
const string enable_picture100 = "images/enabled/picture100.png";
const string picture100 = "images\\enabled\\picture100.png";
Records[picture100].ReplaceContents(imagesPath, enable_picture100, content.FileRoot);
const string enable_picture101 = "images/enabled/picture101.png";
const string picture101 = "images\\enabled\\picture101.png";
Records[picture101].ReplaceContents(imagesPath, enable_picture101, content.FileRoot);
const string enable_picture102 = "images/enabled/picture102.png";
const string picture102 = "images\\enabled\\picture102.png";
Records[picture102].ReplaceContents(imagesPath, enable_picture102, content.FileRoot);
UpdateImage();
}
break;
}
}
catch (Exception ex)
{
//ignored
}
}
Thank you!

List<string> fileNames = new List<string>(); //suppose you have names of files in a list
foreach(var name in fileNames)
{
if(checkBox.IsChecked)
{
Records[name].ReplaceContents
("images/disabled/" + name, "images\\disabled\\" + name, content.FileRoot);
}
else
{
Records[name].ReplaceContents
("images/enabled/" + name, "images\\enabled\\" + name, content.FileRoot);
}
}

Using the code below you can specify a directory (where the string says "FilePath". It gets all files with the extension .png
Then it checks once if the checkbox is checked or not.
And then loops over all the files in the enumerator
var allPngFilesInGivenDirectory = Directory.EnumerateFiles("FilePath").Where(x => x.ToLower().EndsWith(".png"));
var fileEnumerable = allPngFilesInGivenDirectory.GetEnumerator();
string partialPath = checkBox.IsChecked ? "enabled" : "disabled";
while (fileEnumerable.MoveNext())
{
string file = Path.GetFileName(fileEnumerable.Current);
string disable_picture = "images/" + partialPath + "/" + file;
string picture = "images\\" + partialPath + "\\" + file;
Records[picture].ReplaceContents(imagesPath, disable_picture, content.FileRoot);
UpdateImage();
}

Is this roughly what you are looking for?
string pictureName;
string newPictureName;
List<string> fileNames = new List<string>();
foreach(var name in fileNames)
{
if (checkBox.IsChecked)
{
pictureName = "images\\disabled\\" + name + ".png";
newPictureName = "images/disabled/" + name + ".png";
}
else
{
pictureName = "images\\enabled\\" + name + ".png";
newPictureName = "images/enabled/" + name + ".png";
}
}
Records[pictureName].ReplaceContents(imagesPath, newPictureName, content.FileRoot);
Let me know if not.

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 to save multiple image names into database by using dropzone?

I am using dropzone to upload the images. image will be uploaded to server folder while image name will be saved in database table.
here is my code :
public class FormUploader_dz : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string dirFullPath = HttpContext.Current.Server.MapPath("/images/");
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
numFiles = numFiles + 1;
string str_image = "";
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
// int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
fileExtension = System.IO.Path.GetExtension(fileName);
str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("/images/") + str_image;
file.SaveAs(pathToSave_100);
Service.SaveImage(strFileName, context.Session["Id"].ToString());
}
}
context.Response.Write(str_image);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Service file code : which will insert image name into table.
public static void SaveImage(string strImage, string Id)
{
string strSql = #"update tablename set image=#image where id=#Id
";
SqlParameter[] objSqlParameter ={
new SqlParameter("#image",strImage),
new SqlParameter("#Id",Id)
};
SqlHelper.ExecuteNonQuery(strConnectionString, CommandType.Text, strSql, objSqlParameter);
}
Now here problem is i have 4 columns in table to save 4 different image name. what i am actually doing is allowing user to upload max 4 images. i have 4 columns as img1, img2, img3, img4.
here how to insert/update image name into table, as their are 4 diffrent columns for images!
here if user wants he can upload 4 images. so how to decide that in which column the image name will go?????
any suggestions??????
I am not sure about the exact syntax but something like this could work.
// **********************************
int counter = 0; // set up the counter
// **********************************
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
// int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
// **********************************
counter++; // increment the counter
// **********************************
fileExtension = System.IO.Path.GetExtension(fileName);
str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("/images/") + str_image;
file.SaveAs(pathToSave_100);
// **********************************
Service.SaveImage(strFileName, context.Session["Id"].ToString(), counter); // add counter variable to the path.
// **********************************
}
}
// **********************************
// add a column variable and then add it to your column name. like string columnName = "img+columnCount"
// **********************************
public static void SaveImage(string strImage, string Id, int columnCount)
{
// **********************************
string strSql = #"update tablename set img#columnName=#image where id=#Id";
// **********************************
SqlParameter[] objSqlParameter ={
new SqlParameter("#strImage",strImage),
new SqlParameter("#Id",Id)
};
SqlHelper.ExecuteNonQuery(strConnectionString, CommandType.Text, strSql, objSqlParameter);
}

The given path's format is not supported - IE8

Trying to upload an excel file. The code works fine in chrome & firefox. It throws up the above error in IE8. How can I fix this.
private const string ExcelUploadPath = "~/UploadedFiles/";
private void SomeFunction()
{
string dirPath = Server.MapPath(ExcelUploadPath);
string ErrorMsg = SaveUploadedFile(fupCtrl, dirPath)
}
private string SaveUploadedFile(FileUpload fupCtrl, string dirPath)
{
try
{
string sFileName = "";
Random ranObj = null;
int nRandomNum = 0;
ranObj = new Random();
nRandomNum = ranObj.Next();
sFileName = fupCtrl.PostedFile.FileName;
sFileName = sFileName.Substring(0, sFileName.LastIndexOf(".") - 1);
sFileName = sFileName + "_" + nRandomNum.ToString();
sFileName = sFileName +
fupCtrl.FileName.Substring(fupCtrl.FileName.LastIndexOf("."));
fupCtrl.SaveAs(dirPath + sFileName); //exception here
return sFileName;
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
The FileUpload.PostedFile.FileName returns the full file name on the client (including path)
The Path class offers numerous methods to work with strings that represent paths.
sFileName = Path.GetFileNameWithoutExtension(fupCtrl.PostedFile.FileName);
sFileName += "_" + nRandomNum.ToString();
sFileName += Path.GetExtension(fupCtrl.FileName);
fupCtrl.SaveAs(Path.Combine(dirPath, sFileName));
Try this, it can be work.
private const string ExcelUploadPath = "~//UploadedFiles//";
HttpPostedFile postedFile = context.Request.Files[FileObject];
string filename = Path.GetFileNameWithoutExtension(postedFile.FileName);

How to check parent folder

I have get my website path using HttpRuntime.AppDomainAppPath (like this C:/personal/Website/page.aspx)
Web service is always located on page.aspx parent of parent folder (like this C:/personal/Service/service.asmx ). I get the webservice-path using a ABC.dll in servicePath variable like this string servicePath="C:/personal/Service/service.asmx".
How to check service path against website path?
If (GetWebPath()== GetServicePath())
{
// ... do something
}
private string GetWebPath()
{
string path = HttpRuntime.AppDomainAppPath;
string[] array = path.Split('\\');
string removeString = "";
for(int i = array.Length; --i >= 0; )
{
removeString = array[array.Length - 2];
break;
}
path = path.Replace(#"\" + removeString + #"\", "");
return path;
}
private string GetServicePath()
{
string path = #"C:\MNJ\OLK\ABC.asmx"
string[] array = path.Split('\\');
string removeString = "";
for(int i = array.Length; --i >= 0; )
{
removeString = #"\" + array[array.Length - 2] + #"\" + array[array.Length - 1];
path = path.Replace(removeString, "");
break;
}
return path;
}
string webPath = #"C:\blabla\CS_Web\website\";
string servicePath = #"C:\blabla\CS_Web\SPM\Server.asmx";
if(Path.GetDirectory(Path.GetDirectoryName(servicePath))==Path.GetDirectoryName(webPath)
{
//You do something here
}
You have to up page to parent folder using Path.GetDirectoryName()
Try this:
System.Web.Server.MapPath(webPath);
This will return the physical file path of the currently executing web file.
More information can be found here: System.Web.Server
Providing you want to check the following pathes:
string webPath = #"C:\blabla\CS_Web\website\";
string servicePath = #"C:\blabla\CS_Web\SPM\Server.asmx";
you should call
string webPathParentDir = GetParentDirectoryName(webPath);
string servicePathParentDir = GetParentDirectoryName(servicePath);
if (servicePathParentDir.Equals(webPathParentDir, StringComparison.OrdinalIgnoreCase))
{
// ... do something
}
with method:
private string GetParentDirectoryName(string path)
{
string pathDirectory = Path.GetDirectoryName(servicePath);
return new DirectoryInfo(pathDirectory).Parent.FullName;
}

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