Is it possible to read file with attribute hidden in program? I know the path to file.
For example, if I copy a file to some place and set the attribute hidden:
File.Copy("sender.exe", path+"system.exe");
File.SetAttributes(path + "sender.exe", FileAttributes.Hidden);
Can I run the hidden .EXE file with this code (if I know path)?
function Run(path, lang, city) {
var shell = new ActiveXObject("WScript.Shell");
shell.run(path + " " + city + " " + lang);
}
Yes; that's perfectly possible.
Related
This is my first C# script and first non-SQL based script in general.I'm really proud of it (and I couldn't have done it this quickly without help from this community, thanks!), but I know it's going to be all kinds of messy.
The script loops through all files in a single directory, removes special characters from the file names, and renames the files to a standard, user-friendly, name. The script is looking for a specific set of files in the directory. If it finds a file that isn't supposed to be in the directory, it moves the file to a safe folder and renames it. If the folder
I'm working with 4 files that have dynamic names that will include numbers and special characters. The renaming process happens in two steps:
Remove special characters and numbers from the name. Ex: From "EOY 12.21.2018 - 12.28.2018 PRF.xls" to "EOYPRF.xls"
Rename the file to clearly label what the file is. Ex: From "EOYPRF.xls" to "EOY_CompanyName.xls"
There may be files added to this directory by accident, and since they are payroll files, they are highly confidential and cannot be moved unless they need to be moved (only if they are one of the 4 files), so I move them to a subdirectory in the same directory the files are stored in and rename them.
I am also trying to account for if my script or process messes up midway. This script is part of a larger automation process run in SSIS, so there are many failure points. It may be possible that the script fails and leaves one or all of the 4 files in the directory. If this is the case, I need to move the file out of the main directory before the user adds new, unaltered master files to be processed. If the directory contains files of the same final name ("EOY_CompanyName.xls") then it will not work properly.
I'm testing the script by placing the three scenario in the directory.
2 files that are not in any way associated with the 4 master files.
4 unaltered master files formatted with numbers and special characters: "EOY 12.21.2018 - 12.28.2018 PRF.xls"
4 master files already in their final state (simulating a failure before the files are moved to their final directory). Ex: "EOY_CompanyName.xls"
The problem I'm facing is in the rare scenario where there are both unaltered master files and final master files in the directory, the script runs up until the first unaltered file, removes the special characters, then fails at the final renaming step because a file already exists with the same name (Scenario 3 from the 3 points above). It'll then continue to run the script and will move one of the master files into the unexpected file directory and stop processing any other files for some reason. I really need some help from someone with experience.
I've tried so many things, but I think it's a matter of the order in which the files are processed. I have two files named "a.xls" and "b.xls" which are placeholders for unexpected files. They are the first two files in the directory and always get processed first. The 3rd file in the directory is the file named above in its unaltered form ("EOY 12.21.2018 - 12.28.2018 PRF.xls"). It gets renamed and moved into the unexpected files folder, but really it should be passed over to move the master files containing the final name ("EOY_CompanyName.xls") into the unexpected folder. I want to make sure that the script only processes new files whenever it's run, so I want to move any already processed files that failed to get moved via the script into another directory.
public void Main()
{
///Define paths and vars
string fileDirectory_Source = Dts.Variables["User::PayrollSourceFilePath"].Value.ToString();
string fileDirectory_Dest = Dts.Variables["User::PayrollDestFilePath"].Value.ToString();
string errorText = Dts.Variables["User::errorText"].Value.ToString();
DirectoryInfo dirInfo_Source = new DirectoryInfo(fileDirectory_Source);
DirectoryInfo dirInfo_Dest = new DirectoryInfo(fileDirectory_Dest);
string finalFileName = "";
List<string> files = new List<string>(new string[]
{
fileDirectory_Source + "EOY_PRF.xls",
fileDirectory_Source + "EOY_SU.xls",
fileDirectory_Source + "FS_PRF.xls",
fileDirectory_Source + "FS_SU.xls"
});
Dictionary<string, string> fileNameChanges = new Dictionary<string, string>();
fileNameChanges.Add("EOYReportPRF.xls", "EOY_PRF.xls");
fileNameChanges.Add("PayrollEOY.xls", "EOY_SU.xls");
fileNameChanges.Add("PRFFundingStatement.xls", "FS_PRF.xls");
fileNameChanges.Add("SUFundingStatement.xls", "FS_SU.xls");
///Determine if all files present
int count = dirInfo_Source.GetFiles().Length;
int i = 0;
///Loop through directory to standardize file names
try
{
foreach (FileInfo fi in dirInfo_Source.EnumerateFiles())
{
string cleanFileName = Regex.Replace(Path.GetFileNameWithoutExtension(fi.Name), "[0-9]|[.,/ -]", "").TrimEnd() + fi.Extension;
File.Move(fileDirectory_Source + Path.GetFileName(fi.Name), fileDirectory_Source + cleanFileName);
///Move unexpectd files in source directory
if (!fileNameChanges.ContainsKey(cleanFileName))
{
errorText = errorText + "Unexpected File: " + cleanFileName.ToString() + " moved into the Unexpected File folder.\r\n";
File.Move(dirInfo_Source + cleanFileName, dirInfo_Source + "Unexpected Files\\" + Path.GetFileNameWithoutExtension(cleanFileName) + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + fi.Extension);
}
if (fileNameChanges.ContainsKey(cleanFileName))
{
///Final Friendly File Name from Dict
var friendlyName = fileNameChanges[cleanFileName];
///Handle errors produced by files that already exist
if (files.Contains(fileDirectory_Source + friendlyName))//File.Exists(fileDirectory_Source + friendlyName))
{
MessageBox.Show("File.Exists(dirInfo_Source + friendlyName)" + File.Exists(dirInfo_Source + friendlyName).ToString() + " cleanFileName " + cleanFileName);
errorText = errorText + "File already exists: " + friendlyName.ToString() + " moved into the Unexpected File folder.\r\n";
File.Move(dirInfo_Source + friendlyName, dirInfo_Source + "Unexpected Files\\" + Path.GetFileNameWithoutExtension(friendlyName) + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetExtension(friendlyName));
return;
}
///Rename files to friendly name
File.Move(dirInfo_Source + cleanFileName, dirInfo_Source + friendlyName);
finalFileName = friendlyName.ToString();
}
///Count valid PR files
if (files.Contains(dirInfo_Source + finalFileName))
{
i++;
}
}
///Pass number of files in source folder to SSIS
Dts.Variables["User::FilesInSourceDir"].Value = i;
}
catch (Exception ex)
{
errorText = errorText + ("\r\nError at Name Standardization step: " + ex.Message.ToString()) + $"Filename: {finalFileName}\r\n";
}
///Search for missing files and store paths
try
{
if (i != 4)
{
var errors = files.Where(x => !File.Exists(x)).Select(x => x);
if (errors.Any())
errorText = (errorText + $" Missing neccessary files in PR Shared drive. Currently {i} valid files in directory.\r\n\n" + "Files missing\r\n" + string.Join(Environment.NewLine, errors) + "\r\n");
}
}
catch (Exception ex)
{
errorText = errorText + ("Error at Finding Missing PR Files step: " + ex.Message.ToString()) + "\r\n\n";
throw;
}
///Loop through directory to move files to encrypted location
try
{
if (i == 4)
foreach (FileInfo fi in dirInfo_Source.EnumerateFiles())
{
fi.MoveTo(fileDirectory_Dest + Path.GetFileName(fi.FullName));
}
}
catch (Exception ex)
{
errorText = errorText + ("Error at Move Files to Encrypted Directory step: " + ex.Message.ToString()) + "\r\n";
}
Dts.TaskResult = (int)ScriptResults.Success;
Dts.Variables["User::errorText"].Value = errorText;
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
I would ideally like to move all files that are in the folder before the files need to be cleaned and renamed so I dont receive errors or commit records to the database that already exist.
If you made it this far, thank you for your time and I appreciate you taking the hour it probably took to read this. You are a hero.
As I understand you want to move out any of the "4 short names" if they already exist before doing anything else. I would go with below, please note, I did not run the code..
I hope I understood you correct
///Loop through directory to standardize file names
try
{
//Cleanup source folder
foreach (string fileShortName in files)
{
if (File.Exists(fileDirectory_Source + fileShortName))
{
//Time to move the file, its old
errorText = errorText + "Old File: " + fileShortName + " moved into the Old File folder.\r\n";
File.Move(dirInfo_Source + fileShortName, dirInfo_Source + "Old Files\\" + Path.GetFileNameWithoutExtension(fileShortName) + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetExtension(fileShortName));
}
}
foreach (FileInfo fi in dirInfo_Source.GetFiles())
I'm trying to take input and convert that to a .csv file then create a directory for the folder and save that file within the directory. Once I run my code, I'm able to create the directory and file. However, this is supposed to happen after I click the button and does so before. The exception is thrown right after I click the button. I'm using WPF and coding in C#. What would cause this exception?
Here is a snippet
private void updateBANKEevent(object sender, RoutedEventArgs e)
{
//Convert input to CSV format
string userInput = tellerID.Text + "," + vaultSerial.Text + "," + QR.Text;
var bnkDir = #"C:\Program Files\Bank_Data";
//generate headers for CSV file
if (!Directory.Exists(bnkDir))
{
string bnkHeader = "tellerID" + "," + "Vault Serial Number" + "," + "QR Code" + Environment.NewLine;
Directory.CreateDirectory(bnkDir); <--Exception is thrown here
File.WriteAllText(System.IO.Path.Combine(bnkDir,"Bank_Data.csv"), bnkHeader + userInput);
}
// Append new input to existing file
File.AppendAllText(System.IO.Path.Combine(bnkDir),userInput + Environment.NewLine);
}
The exception is quite clear. The user is not authorised to create the specified directory.
Given that the folder is "C:\Program Files\Bank_Data" it will be the case that a regular user won't have the rights to create files or directories whereas an admin user (which you probably are) will.
You need to choose a folder that all users have rights to to store your data, which by default will be %APPDATA%\<your app>.
I am trying to make to create a .cmd file with this code into it: call .\CopyToTarget.cmd w60 glb "C:\Users\oma\me\trunk-r664\USB-map". I am creating this code ~5 times.
But since \trunk-r664\ is already in use it seems like I cannot write: #"\trunk-r664\USB-map" into the .cmd file for some reason. Does anyone know how to fix it? It keeps getting me the error: UnauthorizedAccesExpection was unhandled, ccess to the path 'C:\Users\me\Desktop\trunk-r664\USB-map' is denied.
using (StreamWriter sw = File.CreateText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
+ "\\trunk-r664\\trunk\\cmd\\custom\\RunAll.cmd"))
{
for (int j=0;j<installeerlijst64.Count;j++)
{
sw.WriteLine("call .\\CopyToTarget.cmd " + installeerlijst64[j] + " glb" +
File.CreateText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\trunk-r664\USB-map"));
}
}
I tried this too, but it tells me I am using an illegal character:
"\""+File.CreateText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
+ #"\trunk-r664\USB-map" + "\""));
File.CreateText will create a new file. First time when for loop execute, it will create and open the file USB-map and hold the handle of that file. During second iteration of for loop, it will try to do the same thing. Hence, already in use error.
Remove File.CreateText and you will get the desired result.
sw.WriteLine("call .\\CopyToTarget.cmd " + installeerlijst64[j] + " glb " + "\"" +
Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\trunk-r664\USB-map" + "\"");
Viewing the repository data of TortoiseSVN is done by right click on a file -> TortiseSVN -> Repo-Browser.
I would like to get this data using SharpSVN, in order to retrieve the name of lock owner.
Is it possible? How? Where does this data being saved?
I've tried to get a lock owner name using the following code, however, I get the lock infirmation just in case I'm on the machine where the lock was done from. If I'm another user, I cannot get the lock information.
using (SvnClient client = new SvnClient())
{
client.GetInfo(#"path\to\working\copy\file.xml", out info);
SvnLockInfo lc = info.Lock;
if (lc != null)
{
MessageBox.Show("Owner: " + lc.Owner + "\n" +
"Creation time: " + lc.CreationTime + "\n" +
"Comment: " + lc.Comment + "\n" +
"Expiration time: " + lc.ExpirationTime);
}
}
Even when I set the target as the repository URI- instead of path to the local working copy I get the same result:
Uri target = client.GetUriFromWorkingCopy(#"path\to\working\copy\file.xml");
client.GetInfo(target, out info);
The way I can see the lock owner name from another working copy is, as mentioned, by right click on file -> repo-browser.
Any ideas how to perform it programmatically?
Is it possilbe to create temp files and images in asp.net applications using something like this:
If no, how can i do it?
(ImagePB is a previously treated Bitmap)
if (System.IO.File.Exists(System.IO.Path.GetTempPath() + #"img" + imgID.ToString() + "PB" + extencao) == true)
{
try
{
System.IO.File.Delete(System.IO.Path.GetTempPath() + #"img" + imgID.ToString() + "PB" + extencao);
imagePB.Save(System.IO.Path.GetTempPath() + #"img" + imgID.ToString() + "PB" + extencao, imgFormat);
}
catch (Exception)
{ }
}
Yes, GetTempPath() should return a temporary file path, and the code you have posted should work. http://msdn.microsoft.com/en-us/library/system.io.path.gettemppath.aspx has more information about how GetTempPath() get's the path.
Though, it does not verify if the Temp Path directory exists, or is writeable by the application. I haven't run into a situation where GetTempPath() does return an inaccessible path. You'd probably want to account for this in your application to handle this situation.
Also be mindful, this is very possibly C:\Windows\Temp. It could have limited disk space, or deleted at any time by someone else when disk space is needed. You may want to create a temp path within your application, and delete it when you no longer need it.