I'm writing a application that reads Ia directory contents and writes that to a csv file. I'm trying to get a list of certain file extensions from and upload path which contains a csv file and write a list of the filtered extensions to a new csv file.
I cant figure out how to get the filtered csv file written.....
Here's my method.
StringBuilder CreateUserFileUploadList(SLDocument document, StringBuilder destroyWorksheet)
{
document.SelectWorksheet("User Folder");
var stats = document.GetWorksheetStatistics();
var rowcount = stats.EndRowIndex + 1;
List unwantedExtensions = cblExtensions.Items.Cast().Where(li => li.Selected).Select(li => li.Text).ToList();
if (!String.IsNullOrEmpty(tbOtherExtensions.Text))
{
unwantedExtensions.AddRange(tbOtherExtensions.Text.ToUpper().Split(new char[] { ',', ' ', '.' }, StringSplitOptions.RemoveEmptyEntries));
}
unwantedExtensions.AddRange("EXE,COM,BAT,JS,VBS,PIF,CMD,DLL,OCX,PWL".Split(new char[] { ',', ' ', '.' }, StringSplitOptions.RemoveEmptyEntries));
// new CSV file
var workSheet = new StringBuilder();
workSheet.AppendLine("FILEPATH,Client,Matter,LAST MODIFIED DATE,CREATED DATE,CREATED BY,LAST MODIFIED BY,FOLDER,DOCUMENT NAME,Author,Practice Area,Document Type,ACCESS,Keywords - Comments");
// loop through the directories
for (int i = 2; i 100 chars, or including TAB / \ : * ? " |
// Folder has folders>500 or has files>1000
//TODO: this loops through leaf folders; we need to check intermediate folders to ensure they don't have too many files or folders or a bad name
//Took out #"\",
bool invalidFolderName = new string[] { "/", ":", "*", "?", "" }.Any(s => directoryName.Contains(s));
if (invalidFolderName || directoryName.Length > 200 || files.Count() > 1000)
{
System.Diagnostics.Debug.WriteLine("INVALID folder: " + directoryName);
lblError.Text = lblError.Text + "\r\n" + "INVALID folder: " + directoryName;
//TODO: This should cause the WHOLE upload to fail
}
// build the target folder path
string folder;
string[] stringSeparators = new string[] { tbAuthor.Text };
var path = directoryName.Split(stringSeparators, StringSplitOptions.None);
folder = path.Last();
if (path.Count() > 1)
{
folder = ConfigurationManager.AppSettings["NetDocumentsFolderPath"].ToString() + tbAuthor.Text + #"\User Folder" + folder;
if (folder.Substring(folder.Length - 1, 1) == #"\")
{
folder = folder.Substring(0, folder.Length - 1);
}
}
// Get the files
foreach (var file in files)
{
// Remove unwanted extensions
if (!unwantedExtensions.Contains(file.Extension.Replace(".", "").ToUpper()))
{
var access = file.GetAccessControl();
string user = access.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
//TODO: FWIW, fileName (on netdocs) does NOT need to match the name in the original location...
string fullName = file.FullName;
string fileName = file.Name;
// Wrap in quotes if there are any invalid characters
if (fullName.IndexOfAny(csvTokens) >= 0)
{
fullName = "\"" + fullName.Replace("\"", "\"\"") + "\"";
}
if (fileName.IndexOfAny(csvTokens) >= 0)
{
fileName = "\"" + fileName.Replace("\"", "\"\"") + "\"";
}
if (!document.GetCellValueAsString(i, 2).ToUpper().Contains("DESTROY"))
{
String practiceArea = GetPracticeAreaForClientMatter(document.GetCellValueAsString(i, 2), document.GetCellValueAsString(i, 3));
String documentType = ConfigurationManager.AppSettings["FileDocumentType"].ToString();
// Validate file
// Invalid file names (>200 chars, or TAB / \ : * ? " |
// Invalid file size (>200 MB)
bool invalidFileName = new string[] { "/", #"\", ":", "*", "?", "" }.Any(s => file.Name.Contains(s));
if (invalidFileName || file.Length > 200000000 || file.Name.Length > 200)
{
System.Diagnostics.Debug.WriteLine("INVALID file: " + file.Name);
lblError.Text = lblError.Text + "\r\n" + "INVALID file: " + file.Name;
//TODO: This should cause the WHOLE upload to fail
}
else
{
workSheet.AppendLine(
fullName + "," +
document.GetCellValueAsString(i, 2) + "," +
document.GetCellValueAsString(i, 3) + "," +
file.LastWriteTime + "," +
file.CreationTime + "," +
tbAuthor.Text + "," +
tbAuthor.Text + "," +
folder + "," +
fileName + "," +
tbAuthor.Text + "," +
practiceArea + "," +
documentType + "," +
practiceArea + "|V," +
"Imported from Departed Attorney on: " + DateTime.Now.ToString("G"));
}
}
else
{
destroyWorksheet.AppendLine(fullName);
}
}
}
}
bool invalidFileName = new string[] { "/", #"\", ":", "*", "?", "" }.Any(s => file.Name.Contains(s));
if (document.GetCellValueAsString(i, 2).ToUpper().Contains("DESTROY"))
{// Files in folders marked "destroy" are saved elsewhere
//destroyWorkSheet.Append(string.Format("{0}", "Directory" + fullName));
//destroyWorkSheet.Append(string.Format("{1}", "FileName" + fullName));
// destroyWorkSheet.AppendLine("Directory, FileName");
// destroyWorkSheet.Append(string.Format("{0},{1}", "Directory", "FileName") + fullName);
destroyWorksheet.AppendLine(fullName);
}
// Validate file for name (less than 200 chars, can't have TAB / \ : * ? " | ) and size ( less than 200 MB)
else if (invalidFileName || file.Length > 200000000 || file.Name.Length > 200)
{// This should cause the WHOLE upload to fail
System.Diagnostics.Debug.WriteLine("INVALID file: " + file.Name);
lblError.Text = lblError.Text + "\r\n" + "INVALID file: " + file.Name;
errorWorksheet.AppendLine("INVALID file: " + file.Name);
}
else if (unwantedExtensions.Contains(file.Extension.Replace(".", "").ToUpper()))
{// Files with unwanted extensions are filtered out
filterWorksheet.AppendLine(fullName);
}
Related
I'm trying to create an import file based on a list of files in a directory. The problem is now I've been asked to increment the value of one of the output directories based on a specific part of the file name.
Below the LinkName is hard coded to Full Image_0. I actually want it to be more like LinkName = "Full Image_" + intXYZ.toString();
intXYZ would be a variable that starts at 0 and goes up by 1 for each file with identical PartNums.
Here is relevant code:
ImageName = Directory.GetFiles(#"\\192.168.0.144\iApps_Final_Images\ProductImages\", "*.*", SearchOption.AllDirectories);
ImageItem = Directory.GetFiles(#"\\192.168.0.144\iApps_Final_Images\ProductImages\", "*.*", SearchOption.AllDirectories).Select(file => Path.GetFileNameWithoutExtension(file)).ToArray();
// Set path for output file and open
FilePath = #"\\vhome\public\p21\Images.txt";
var writer = new StreamWriter(FilePath);
// Go through each file found (not named thumbs) and output row of data needed for inv_mast_links import
foreach (var item in ImageName)
{
SetNum = SetNum + 1;
LinkPath = item.ToString();
PartNum = ImageItem[SetNum - 1].ToString().Split('_').Last();
LinkName = "Full Image_0";
var line = SetNum + delimiter + PartNum + delimiter + LinkName + delimiter + LinkPath + delimiter + "Item Maintenance";
if (PartNum != "Thumbs")
{
writer.WriteLine(line);
}
}
// Close the output file
writer.Close();
Example: If files in directory are: TVImage_567.jpg, FrontView_888.jpg, BackView_888.jpg
then since two of the images are for the same PartNum of 888 the desired three LinkName outputs would be: Full Image_0, Full Image_0, Full Image_1.
If I understood your question correctly this is what you want:
Dictionary<string, Integer> counts = new Dictionary<string, Integer>();
foreach (var item in ImageName)
{
SetNum = SetNum + 1;
LinkPath = item.ToString();
PartNum = ImageItem[SetNum - 1].ToString().Split('_').Last();
if (counts.ContainsKey(PartNum)) {
counts[PartNum]++;
}
else
{
counts.Add(PartNum, 0);
}
LinkName = "Full Image_" + counts[PartNum];
var line = SetNum + delimiter + PartNum + delimiter + LinkName + delimiter + LinkPath + delimiter + "Item Maintenance";
if (PartNum != "Thumbs")
{
writer.WriteLine(line);
}
}
It is not quite clear what SetNum does so I just left it there. The idea is simply to store your the previous item's "number" and increment a counter until the actual "number" isn't equal to the previous one.
How about this, You dont require a SetNum
string[] ImageNames = Directory.GetFiles(#"Source-Directory\", "*.*", SearchOption.AllDirectories);
string[] ImageItem = ImageNames.Select(file => Path.GetFileNameWithoutExtension(file)).ToArray();
string FilePath = #"Destination.txt";
using (var writer = new StreamWriter(FilePath))
{
for (int i = 1; i < ImageNames.Length - 1; i++)
{
string LinkPath = ImageNames[i].ToString();
string PartNum = ImageItem[i - 1].ToString().Split('_').Last();
string LinkName = "Full Image_" + i;
var line = i + delimiter + PartNum + delimiter + LinkName + delimiter + LinkPath + delimiter + "Item Maintenance";
if (PartNum != "Thumbs")
{
writer.WriteLine(line);
}
}
}
I'm making a bit of code in Visual Studio to sort my music files (.m4a).
I have a listbox with a list of files on my desktop.
My code loops through each file.
Example files:
[Eminem] Not alone.m4a
[Imagine Dragons] Radioactive.m4a
[Dragon Force] Through Fire and Flames.m4a
if (file.Contains(".m4a"))
{
stat_sorted_audio++;
var artist = file.Split(new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries);
bool exists = System.IO.Directory.Exists(#folder_music + artist[0] + "\\");
if (!exists)
{
System.IO.Directory.CreateDirectory(#folder_music + artist[0] + "\\");
}
string s_file = file.Replace("[" + artist[0] + "]", "");
string s_target = folder_music + artist[0] + "\\";
string s_source = folder_desktop + file;
label2.Text = s_file + "\n" + s_target + "\n" + s_source;
moveFile(s_source, s_target, s_file, ".m4a");
}
And the function to move files:
public void moveFile(string source, string target, string file)
{
if (!System.IO.File.Exists(target+file))
{
System.IO.File.Move(#source, #target + file);
}
}
This works fine and I end up with the files in the correct folder, but once the files have moved a padlock is appearing next to the icon, I don't want this.
Does anyone know why this is happening?
File delete problem - please help me i cant delete a file .. when i try to delete the i get this massage
c# File.Delete - File being used by another processc# File.Delete -
File being used by another process
protected void Button2_Click1(object sender, EventArgs e)
{
HttpFileCollection hfc = Request.Files;
string x = "";
string foldername = DateTime.Now.ToString().Trim().Replace(" ", "").Replace(":", "").Replace("/", "");
string foldername1 = foldername+"1";
Directory.CreateDirectory(Server.MapPath("~/IMAGEUPLOADCENTER/") + foldername);
Directory.CreateDirectory(Server.MapPath("~/IMAGEUPLOADCENTER/") + foldername1);
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string name =(DateTime.Now.ToString() + i + hpf.FileName).ToString().Trim().Replace(" ", "").Replace(":", "").Replace("/", "");
hpf.SaveAs(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername + "/") + name);
ResizeImageWidth(497, Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername + "/") + name, Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name);
System.Drawing.Image upImage = System.Drawing.Image.FromFile(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name); //System.Drawing.Image.FromStream(FU1.PostedFile.InputStream);
System.Drawing.Image logoImage = System.Drawing.Image.FromFile(Server.MapPath("~/pages002248Xc54/UploadImages/LOGOnew.png"));
using (Graphics g = Graphics.FromImage(upImage))
{
g.DrawImage(logoImage, new Point(upImage.Width - logoImage.Width - 10, 10));
upImage.Save(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername + "/") + name);
File.Delete(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name);
// Image1.ImageUrl = "~/UploadFiles/2" + "//" + fileName;
}
x = x + "</br><img src='http://hela.co.il/IMAGEUPLOADCENTER/" + foldername + "/" + name + "'/></br>";
}
}
TextArea1.InnerText = x;
FileUpload1.Visible = false;
Button2.Visible = false;
}
Your file is being locked by you and that is preventing you from deleting it. The Image.FromFile method locks the file used to create the object until the Image object is disposed of. So in this case, the image file will remain locked until you dispose of upImage.
Move your File.Delete to after you're done with the image and it will work. In the code below, I added using statements to each variable so that they will get disposed of (and unlock the file), and then I moved the delete statement outside of the using block (after the Image objects are disposed of).
using(System.Drawing.Image upImage = System.Drawing.Image.FromFile(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name))
using(System.Drawing.Image logoImage = System.Drawing.Image.FromFile(Server.MapPath("~/pages002248Xc54/UploadImages/LOGOnew.png")))
using (Graphics g = Graphics.FromImage(upImage))
{
g.DrawImage(logoImage, new Point(upImage.Width - logoImage.Width - 10, 10));
upImage.Save(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername + "/") + name);
}
File.Delete(Server.MapPath("~/IMAGEUPLOADCENTER/" + foldername1 + "/") + name);
Image.FromFile Method (String)
using statement (C#)
private void button4_Click(object sender, EventArgs e)
{
FileStream outputFileStream = new FileStream("log.txt", FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(outputFileStream);
// writing block
string originalPathFile = #"C:\Users\user\Downloads\CaptchaCollection\Small\";
string duplicatePath = #"C:\Users\user\Downloads\CaptchaCollection\Small\Duplicates\";
string movedOriginal = #"C:\Users\user\Downloads\CaptchaCollection\Small\Sorted\";
var files = Directory.GetFiles(originalPathFile)
.Select(nameWithExtension => Path.GetFileNameWithoutExtension(nameWithExtension))
.Where(name => { int number; return int.TryParse(name, out number); })
.Select(name => int.Parse(name))
.OrderBy(number => number).ToArray();
while (files.Length > 1)
{
string duplicateOfFolder = Directory.CreateDirectory(duplicatePath + files[0].ToString()).FullName;
for (int j = 1; j < files.Length; j++)
{
Bitmap im1 = new Bitmap(originalPathFile + files[0].ToString() + ".png");
Bitmap im2 = new Bitmap(originalPathFile + files[j].ToString() + ".png");
if (compare(im1, im2))
{
File.Move(originalPathFile + files[j].ToString() + ".png", duplicateOfFolder + files[j].ToString() + ".png");
writer.WriteLine(files[j].ToString() + ".png" + " is a duplicate of " + files[0].ToString() + ".png \n");
}
}
File.Move(originalPathFile + files[0].ToString() + ".png", movedOriginal + files[0].ToString() + ".png");
writer.WriteLine(files[0].ToString() + ".png " + "has had its duplicates removed.");
files = Directory.GetFiles(originalPathFile)
.Select(nameWithExtension => Path.GetFileNameWithoutExtension(nameWithExtension))
.Where(name => { int number; return int.TryParse(name, out number); })
.Select(name => int.Parse(name))
.OrderBy(number => number).ToArray();
}
writer.Close();
outputFileStream.Close();
}
So this button basically moves duplicate files of an image visually. I got this code from one of my previous questions I've asked. Now I want to use a new folder to place duplicates of a specific image.
For example:
1.png has 5 visual duplicates (65.png,87.png,100.png,103.png,156.png). I want to move all the duplicates to this directory instead of just placing it in the Duplicates directory: C:\Users\user\Downloads\CaptchaCollection\Small\Duplicates\1\
Now instead what's happening is that it apparently is renaming and regenerating some images. I can't really describe this in words because I can't really see what's going on. What's not happening is that those files are not being moved to the directory of a duplicated file organization.
Folders will create but instead it's not placing it in the proper folder.
If I understood your requirement correctly then I think issue is in following lines.
if (compare(im1, im2))
{
File.Move(originalPathFile + files[j].ToString() + ".png", duplicateOfFolder + files[j].ToString() + ".png");
writer.WriteLine(files[j].ToString() + ".png" + " is a duplicate of " + files[0].ToString() + ".png \n");
}
You are actually comparing first file with others but still copying the files in duplicate folder.
Replace following line
File.Move(originalPathFile + files[j].ToString() + ".png", duplicateOfFolder + files[j].ToString() + ".png");
with
String path = duplicateOfFolder;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
File.Move(originalPathFile + files[j].ToString() + ".png", path + "\\" + files[j].ToString() + ".png");
This should work.
I have Created a small XML tool, to find the numbers of element present in Multiple XML files.
This code gives the fine result for the elements which are must in XML files.
But when it comes to specific elements, which may be present or not in XML files, Software give me result as:
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMF0-004D-P565-00000-00.xml
Instance: 0
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMF0-004D-P566-00000-00.xml
Instance: 0
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMF0-004D-P567-00000-00.xml
Instance: 0
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMG0-004D-P001-00000-00.xml
**Instance: 11**
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMG0-004D-P002-00000-00.xml
Instance: 0
Now here the problem is XML files may be 500-1000 when i search the tag which may be present or not the tool gives me result for each and every files. In this case specific tag present instance may be 0 or multiple.
Can any one suggest the changes in my Code to find the file name in which instance is greater than 0. and if instance > 0 print it in text box.
My current code:
public void SearchMultipleTags()
{
if (txtSearchTag.Text != "")
{
try
{
//string str = null;
//XmlNodeList nodelist;
string folderPath = textBox2.Text;
DirectoryInfo di = new DirectoryInfo(folderPath);
FileInfo[] rgFiles = di.GetFiles("*.xml");
foreach (FileInfo fi in rgFiles)
{
int i = 0;
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(fi.FullName);
//rtbox2.Text = fi.FullName.ToString();
foreach (XmlNode node in xmldoc.GetElementsByTagName(txtSearchTag.Text))
{
i = i + 1;
//
}
rtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";
//rtbox2.Text += fi.FullName + "instances: " + str.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("Invalid Path or Empty File name field.");
}
}
else
{
MessageBox.Show("Dont leave field blanks.");
}
}
If I understand correctly, you want to display text only if the i is greater than 0?
if(i > 0 )
rtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";
Use
if(i > 0)
rtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";
instead of simple
rtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";
You could always just use this code inside the try block:
rtbox2.Text =
String.Join(Environment.NewLine + Environment.NewLine,
from fi in (new DirectoryInfo(textBox2.Text)).GetFiles("*.xml")
let xd = XDocument.Load(fi.FullName)
let i = xd.Descendants(txtSearchTag.Text).Count()
where i > 0
select String.Join(Environment.NewLine, new []
{
DateTime.Now.ToString(),
fi.FullName,
i.ToString(),
}));
Does it all in one line (bar the formatting). :-)