File.Move is adding a padlock to file image - c#

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?

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?

Moving files using SSIS and Script Component

I need to write a code in script component in SSIS that will move files to corresponding folders. Files that I'm getting are usually named, for example "Dem323_04265.45.23.4", "Dem65_459.452.56", "Ec2345_456.156.7894" and I need to move them to a corresponding folders. The name of my folders are "Oklahoma City (323)", "New York(65)".. I need to move those files to matching folders, so for example "Dem323_04265.45.23.4" would go to folder "Oklahoma City (323)". I need to modify my code so the number that is located between first two or three letter and underline matches number located in parenthesis. I've been working on this for several days already and I'm new with ssis and c#, so any help would be appreciated. This is the code I have so far:
public void Main()
{
string filename;
// string datepart;
bool FolderExistFlg;
filename = Dts.Variables["User::FileName"].Value.ToString();
// datepart = (filename.Substring(filename.Length - 12)).Substring(0, 8);
var folderNumber = Regex.Match(
filename,
//Dts.Variables["OutputMainFolder"].Value.ToString(),
#"\(([^)]*)\)").Groups[1].Value;
FolderExistFlg = Directory.Exists(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + folderNumber);
if (!FolderExistFlg)
{
Directory.CreateDirectory(Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + folderNumber);
}
File.Move(Dts.Variables["SourceFolder"].Value.ToString() + "\\" + filename + "\\" + folderNumber,
Dts.Variables["OutputMainFolder"].Value.ToString() + "\\" + filename);
Dts.TaskResult = (int)ScriptResults.Success;
}
#region ScriptResults declaration
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
Here you go, the below snippet would move the files as per the match criteria. You need to take care of the source input as per your configuration.
string filePath = #"C:\Packages\StackOverflow";
//string fileName = string.Empty;
//get list of files
string[] filePaths = Directory.GetFiles(filePath);
//get list of folders
string[] dirPaths = Directory.GetDirectories(filePath);
//loop through the files and move them
foreach(string fileNames in filePaths)
{
string[] pathArr = fileNames.Split('\\');
string fileName = pathArr.Last().ToString();
int index = fileName.IndexOf('_');
string fileNamePart = fileName.Substring(0, index);
//get the first numeric part of the filename to perform the match
var fileNameNumPart = Regex.Replace(fileNamePart, "[^0-9]", "");
//find related directory
var dirMatch = dirPaths.FirstOrDefault(stringToCheck => stringToCheck.Contains(fileNameNumPart.ToString()));
if (dirMatch != null)
{
// move would fail if file already exists in destination
if (!File.Exists(dirMatch + '\\' + fileName))
{
File.Move(fileNames, dirMatch + '\\' + fileName);
}
}
}

IOException when moving an image file

private void MoveFile(string destination, string imagePath)
{
try
{
string source = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["TempImagePath"]);
string[] resizedImage = imagePath.Split('.');
//string compressedImagePath = resizedImage[0] + "_compress." + resizedImage[1];
string thumbnail150Name = resizedImage[0] + "_thumbnail." + resizedImage[1];
string mediumPhoto300Name = resizedImage[0] + "_mediumPhoto." + resizedImage[1];
string largePhotoName = resizedImage[0] + "_largePhoto." + resizedImage[1];
//Move thumbnail
if (System.IO.File.Exists(source + "\\" + thumbnail150Name))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + thumbnail150Name, destination + "\\" + thumbnail150Name);
}
//Move medium sized photo
if (System.IO.File.Exists(source + "\\" + mediumPhoto300Name))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + mediumPhoto300Name, destination + "\\" + mediumPhoto300Name);
}
//Move large photo
if (System.IO.File.Exists(source + "\\" + largePhotoName))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + largePhotoName, destination + "\\" + largePhotoName);
}
//Move original
if (System.IO.File.Exists(source + "\\" + imagePath))
{
if (!System.IO.Directory.Exists(destination))
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(destination);
}
System.IO.File.Move(source + "\\" + imagePath, destination + "\\" + imagePath);
}
}
catch (Exception ex)
{
BgLogger.FileLogger.LogError("In private method : MoveFile(string, string), On server : " + Dns.GetHostName() + " At : " + DateTime.Now, ex).Wait();
}
}
I am using this code while moving an image file. But I am getting the following exception
System.IO.IOException: The process cannot access the file because it
is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalMove(String sourceFileName, String
destFileName, Boolean checkHost) at
BgPortal.Controllers.DriverController.MoveFile(String destination,
String imagePath)
https://u3307993.ct.sendgrid.net/wf/open?upn=mzyvlCvUM5odb-2FP3IS9fxavC9Nq-2BVU-2BlgxLxmreq6Qi5SziY4JAfC5R720TrBfTXj7GdvSOgEG2Qeq-2BGKm-2FwWmPOrbAem6UFnvcBKca-2FzIM3XkXg0dHdke9rhjcAKDqtd0MJQCnmyIN-2Fi-2FXbgygtnXFNxuEuwts4hybPsnVR72PsfW4L6YZ32pnlEuwGMF-2Fcg0S8f8Y7UOBHwDMzh1BgJnhqO9i5dgS9LRZytY4n6TNCt37JAtdi5EOj8OxBqhan
This exception occurs very randomly.
Can anyone help me with this?
The exception is thrown because the file you are trying to move is open by your program or another process. Make sure that you are always closing the file after you finish processing it. Particularly, make sure that you always call Close or Dispose on all FileStream objects when they are no longer needed.
If the file is open by another process (for example by another user) then you can wait for some time and retry moving the file.

GetFiles of certain extension and write to spreadsheet C#

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

c# service renaming files!

I have a windows service , that takes files with metadata(FIDEF) and corresponding video file and , translates the XML(FIDEF) using XSLT .
I get the file directory listing for FIDEF's and if a video file of the same name exists it translates it. That works ok , but it is on a timer to search every minute. I am trying to handle situations where the same file name enters the input directory but is already in the output directory. I just have it changing the output name to (copy) thus if another file enters i should get (copy)(copy).mov but the service won't start with filenames of the same directory already in the output , it works once and then does not seem to pick up any new files.
Any Help would be great as I have tried a few things with no good results. I believe its the renaming methods, but I've put most of the code up in case its a clean up issue or something else.
(forgive some of the names just trying different things).
private void getFileList()
{
//Get FILE LIST FROM Directory
try
{
// Process Each String/File In Directory
string result;
//string filename;
filepaths = null;
filepaths = Directory.GetFiles(path, Filetype);
foreach (string s in filepaths)
{
for (int i = 0; i < filepaths.Length; i++)
{
//Result Returns Video Name
result = Path.GetFileNameWithoutExtension(filepaths[i]);
FileInfo f = new FileInfo(filepaths[i]);
PreformTranslation(f, outputPath + result , result);
}
}
}
catch (Exception e)
{
EventLog.WriteEntry("Error " + e);
}
}
private void MoveVideoFiles(String Input, String Output)
{
File.Move(Input, Output);
}
private string GetUniqueName(string name)
{
//Original Filename
String ValidName = name;
//remove FIDEF from filename
String Justname1 = Path.GetFileNameWithoutExtension(name);
//get .mov extension
String Extension2 = Path.GetExtension(Justname1);
//get filename with NO extensions
String Justname = Path.GetFileNameWithoutExtension(Justname1);
//get .Fidef
String Extension = Path.GetExtension(name);
int cnt = 0;
//string[] FileName = Justname.Split('(');
//string Name = FileName[0];
while (File.Exists(ValidName)==true)
{
ValidName = outputPath + Justname + "(Copy)" + Extension2 + Extension;
cnt++;
}
return ValidName;
}
private string getMovFile(string name)
{
String ValidName = name;
String Ext = Path.GetExtension(name);
String JustName = Path.GetFileNameWithoutExtension(name);
while(File.Exists(ValidName))
{
ValidName = outputPath + JustName + "(Copy)" + Ext;
}
return ValidName;
}
//Preforms the translation requires XSL & FIDEF name.
private void PreformTranslation(FileInfo FileName, String OutputFileName , String result)
{
string FidefName = OutputFileName + ".FIDEF";
String CopyName;
String copyVidName = outputPath + result;
XslCompiledTransform myXslTransform;
myXslTransform = new XslCompiledTransform();
try
{
myXslTransform.Load(XSLname);
}
catch
{
EventLog.WriteEntry("Error in loading XSL");
}
try
{ //only process FIDEF's with corresponding Video file
if (AllFidef == "no")
{
//Check if video exists if yes,
if (File.Exists(path + result))
{
//Check for FIDEF File Already Existing in the Output Directory.
if (File.Exists(FidefName))
{
//Get unique name
CopyName = GetUniqueName(FidefName);
copyVidName= getMovFile(copyVidName);
//Translate and create new FIDEF.
//double checking the file is here
if (File.Exists(outputPath + result))
{
myXslTransform.Transform(FileName.ToString(), CopyName);
File.Delete(FileName.ToString());
MoveVideoFiles(path + result, copyVidName);
}
////Move Video file with Corresponding Name.
}
else
{ //If no duplicate file exsists in Directory just move.
myXslTransform.Transform(FileName.ToString(), OutputFileName + ".FIDEF");
MoveVideoFiles(path + result, outputPath + result);
}
}
}
else
{
//Must have FIDEF extension
//Processes All FIDEFS and moves any video files if found.
myXslTransform.Transform(FileName.ToString(), OutputFileName + ".FIDEF");
if (File.Exists(path + result))
{
MoveVideoFiles(path + result, outputPath + result);
}
}
}
catch (Exception e)
{
EventLog.WriteEntry("Error Transforming " + "FILENAME = " + FileName.ToString()
+ " OUTPUT_FILENAME = " + OutputFileName + "\r\n" +"\r\n"+ e);
}
}
There is a lot wrong with your code. getFileList has the unneeded inner for loop for starters. Get rid of it. Your foreach loop has s, which can replace filepaths[i] from your for loop. Also, don't do outputPath + result to make file paths. Use Path.Combine(outputPath, result) instead, since Path.Combine handles directory characters for you. Also, you need to come up with a better name for getFileList, since that is not what the method does at all. Do not make your method names liars.
I would simply get rid of MoveVideoFiles. The compiler just might too.
GetUniqueName only works if your file name is of the form name.mov.fidef, which I'm assuming it is. You really need better variable names though, otherwise it will be a maintenance nightware later on. I would get rid of the == true in the while loop condition, but that is optional. The assignment inside the while is why your files get overwritten. You always generate the same name (something(Copy).mov.fidef), and as far as I can see, if the file exists, I think you blow the stack looping forever. You need to fix that loop to generate a new name (and don't forget Path.Combine). Maybe something like this (note this is untested):
int copyCount = 0;
while (File.Exists(ValidName))
{
const string CopyName = "(Copy)";
string copyString = copyCount == 0 ? CopyName : (CopyName + "(" + copyCount + ")");
string tempName = Justname + copyString + Extension2 + Extension;
ValidName = Path.Combine(outputPath, tempName);
copyCount++;
}
This generates something(Copy).mov.fidef for the first copy, something(Copy)(2).mov.fidef for the second, and so on. Maybe not what you want, but you can make adjustments.
At this point you have a lot to do. getMovFile looks as though it could use work in the same manner as GetUniqueName. You'll figure it out. Good luck.

Categories