WPF: unable to map network drive for all users - c#

I'm trying to create a function for an application to automatically copy over specific files during the final stage of a job. The only issue here is that the copy location is a protected share drive and uses a separate login instead of being validated by the active directory so I've got to do a bit of a workaround to get File.Copy() working. My workaround has been to call the built in net.exe utility and passing a command line argument that points to the share drive to open up a connection to the drive then using File.Copy() to get the file where it needs to go then deleting the connection. The issue at hand is that this works great on my computer but when anyone else on the team runs the same program a "Logon failure: unknown user name or bad password" is thrown. I'm at a bit of loss as to why this would happen since the username and password are static and not being changed and everyone on the team has the same network permissions I do. Here is the WPF/C# code I'm using to do this:
try
{
string mrdfDropPath = #"dropPathHere";
string MRDFPath = #"storePath\test.xml";
string command = #"use " + mrdfDropPath + #" /user:CORP\Username Password";
Process.Start("net.exe", command);
File.Copy(MRDFPath, mrdfDropPath + "test.xml");
string command2 = #"use " + mrdfDropPath + #" /delete";
Process.Start("net.exe", command2);
StreamWriter writer = new StreamWriter(#"logPath\log.txt", true);
writer.WriteLine(mrdfDropPath + "test.xml" + "," + File.GetLastWriteTime(MRDFPath).ToString());
writer.Close();
}
catch (Exception e)
{
StreamWriter writer = new StreamWriter(#"logPath\log.txt", true);
writer.WriteLine(e.Message);
writer.Close();
}
Like I said this works as expected during debug and when I run the application, but for anyone else it is throwing the error.

Related

How do i execute an external exe using a specific user

Im making an application which needs to monitor the filesystem using FileSystemWatcher, to detect how an installation affects the filesystem.
To get rid of noise i want to filter the events that are created by their creating user, and that code is working with the //BUILTIN //Administrator user, which is used by default when doing an installation. But still there are quite a bit of noise. Then i got the idea of creating a specific user that i can use for running the installation file, and filter on that specific user, and thereby getting rid of allmost all the noise.
this is my code for the process creation and start
private void executeInnoInstaller(string path, string fileName)
{
// Use ProcessStartInfo class
ProcessStartInfo installerProces = new ProcessStartInfo();
installerProces.CreateNoWindow = true;
installerProces.UseShellExecute = false;
installerProces.FileName = path + "\"" + fileName + "\"";
installerProces.WindowStyle = ProcessWindowStyle.Normal;
installerProces.UserName = "test";
System.Security.SecureString encPassword = new System.Security.SecureString();
foreach (System.Char c in "test")
{
encPassword.AppendChar(c);
}
encPassword.MakeReadOnly();
installerProces.Password = encPassword;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(installerProces))
{
exeProcess.WaitForExit();
//int exitCode = exeProcess.ExitCode;
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
this code exits with a access denied.
OS=Windows
Ive already tried to run the installer.exe from the OS filehandler with SHIFT - Rightclick using the specified user, and it works.
VisualStudio is run as administrator.
Ive tried to run the build project exe file as administrator, but it does not work.
Without the user credentials, the code works and uses the //BUILTIN //Administrator account
Does anybody have any idea ?
Thank you beforehand for your time and effort.
This code works if i turn down the UAC securitylevel to the lowest.

Failed to convert xml to csv using perl script through c#

I have the following code for converting xml to csv by using perl script. When I run the perl script through c# but there is no files are created and string output become empty.
What is the problem?
I have the perl script with .txt extention, Is this ok or not?
string filePath = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())) + "/Files/SAVVIS_CDR_1806012231.XML";
if (Path.GetExtension(filePath) != "csv")
{
ProcessStartInfo perlStartInfo = new ProcessStartInfo(#"C:\Strawberry\perl\bin\perl.exe");
string perlScriptFilePath = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())) + "/PerlScript/formatter_savvis.pl.txt";
string csvFilePath = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())) + "/PerlScript/";
perlStartInfo.Arguments = perlScriptFilePath + " " + filePath + " " + csvFilePath;
perlStartInfo.UseShellExecute = false;
perlStartInfo.RedirectStandardOutput = true;
perlStartInfo.RedirectStandardError = true;
perlStartInfo.CreateNoWindow = false;
Process perl = new Process();
perl.StartInfo = perlStartInfo;
perl.Start();
perl.WaitForExit();
string output = perl.StandardOutput.ReadToEnd();
}
Could you please anyone help me to solve this problem?
Thanks in advance.
First, to find out what went wrong:
string error = perl.StandardError.ReadToEnd();
Also, make sure you have necessary permissions to create files in the output directory. You may try to run your process with Admin privileges to find out if it's a permission issue:
perlStartInfo.Verb = "runas";
You may want to run your entire host process with elevated permissions for this.
(This is only to figure out if it's a permission issue! If it's the case, grant the output directory the necessary permissions, and if possible don't automatically run scripts with admin privileges in production environment)
There also may be errors in the perl script itself.

Programmatically get the full path of a shared folder on another computer?

I know that you can get the path to a mapped drive (e.g. Find UNC path of a network drive?), but what if the only thing I have is just the path to the shared folder?
For example, let's say I have a friend who is sharing the folder C:\MyDocs\PublicDoc over the network. I can access it under the path \\danas-pc\PublicDoc. Is there any way that I could, being on another computer, determine that \\danas-pc\PublicDoc actually maps to \\danas-pc\c$\MyDocs\PublicDoc?
I ask because I am given a path to a log file that has the path (e.g. \danas-pc\c$\MyDocs\PublicDoc\mylog.log )and I need to check if it matches the same path that is set in another location. The other location has the "short path" (e.g. \\danas-pc\PublicDoc\mylog.log ), and thus, even though the log paths lead to the same location, the program determines that they are different. I wanted to see if there's a way to figure out that they are pointing to the same location.
I can't imagine why you might need this since for the remote instance's full path is \danas-pc\PublicDoc but if you let your imagination thrive I'd suggest something like this:
(1) on the remote computer inside the share folder you can drop a small script that if executed return the full path. You have to search for appropriate coding for windows or linux environment also you need to have execution privilege or rights on it. for example on windows you can have a vbscrit or cscript and a .sh script in linux.
Also please note that seeing it from the remote host, in terms of the remote host the full path is \NAME-OR-IP\Path\to\Folder\or\File etc. For you on the remote connection that is the full path ;)
UPDATE:
as per the comment below, this is a full script that does the following
creates a vbscript with code in it to retrieve the current full path
copies the files into the network desired path
executes the vbscript and reads the result back
deletes the vbscript
Assuming: you have the read/write access on the network folder
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace GetNetworkFullPath
{
class Program
{
static void Main(string[] args)
{
var networkFolder = "\\\\REMOTE-PC-NAME\\SharedFolder";
var nameOfVBScript = "capturepath.vbs";
var vbsOutput = "";
//Get the name of the current directory
var currentDirectory = Directory.GetCurrentDirectory();
Console.WriteLine("Current Dir: " + currentDirectory);
//1. CREATE A VBSCRIPT TO OUTPUT THE PATH WHERE IT IS PRESENT
//Ref. https://stackoverflow.com/questions/2129327/how-to-get-the-fully-qualified-path-for-a-file-in-vbscript
var vbscriptToExecute = "Dim folderName \n" +
"folderName = \"\" \n" +
"Dim fso \n" +
"Set fso = CreateObject(\"Scripting.FileSystemObject\") \n" +
"Dim fullpath \n" +
"fullpath = fso.GetAbsolutePathName(folderName) \n" +
"WScript.Echo fullpath \n";
//Write that script into a file into the current directory
System.IO.File.WriteAllText(#""+ nameOfVBScript + "", vbscriptToExecute);
//2. COPY THE CREATED SCRIPT INTO THE NETWORK PATH
//Ref. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-copy-delete-and-move-files-and-folders
string sourceFile = System.IO.Path.Combine(currentDirectory, nameOfVBScript);
string destFile = System.IO.Path.Combine(networkFolder, nameOfVBScript);
System.IO.File.Copy(sourceFile, destFile, true);
//3. EXECUTE THAT SCRIPT AND READ THE OUTPUT
//Ref. https://stackoverflow.com/questions/27050195/how-do-i-get-the-output-from-my-vbscript-console-using-c
Process scriptProc = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.WorkingDirectory = #"" + networkFolder + "";
info.FileName = "Cscript.exe";
info.Arguments = nameOfVBScript;
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
info.WindowStyle = ProcessWindowStyle.Hidden;
scriptProc.StartInfo = info;
scriptProc.Start();
scriptProc.WaitForExit();
bool exit = false;
while (!scriptProc.StandardOutput.EndOfStream)
{
vbsOutput = scriptProc.StandardOutput.ReadLine();
}
Console.WriteLine("vbscript says: " + vbsOutput);
//4. DELETE THE FILE YOU JUST COPIED THERE
System.IO.File.Delete(#"" + networkFolder + "\\" + nameOfVBScript);
}
}
}
Unfortunately when executed remotely the script replies with the Network Path :( so disappointed...really sorry! As long as execution is happening from a user outside the remote system it will reply with the absolute path related to that instance. I think an internal process/user should execute the file and reply back with the answer to the application.
I'll try to think something more tomorrow and maybe reply back if I'm lucky.

Inconsistent results during debugging - Web API

I have some code that uses a library for a product called Fusion Pro. Based on some config and data files it will generate a PDF file. I have been getting consistent result of a complete lack of output without any thrown exceptions. However when debugging I have been able to get the PDF to generate by attaching the debugger to the code running in my local IIS and stepping through line by line. Nothing is consistent though. It seems to have a higher success rate if I use F11 instead of F10 and going "slow but steady" through each line. Unfortunately it doesn't always produce a PDF even with stepping through the code.
I have never experienced code behaving so inconstantly with the same inputs each time.
The only other relevant bits of information is this code is working in another asmx service without issue, it is running under a specific domain account (requires special security), and it is running in 32bit mode.
DLQueueClient client = new DLQueueClient();
DLQueueJob vdpQueueJob = new DLQueueJob();
string fileName = message.OutputFilePath;
var dataFilePath = CreateDataFile(fileName, message.DefFilePath, message.VariableDataContent, message.QTY);
var pdfFilePath = Path.Combine(new[] { message.OutputFilePath, dataFilePath.Replace(".txt", ".pdf") });
vdpQueueJob.Priority = priority;
vdpQueueJob.Queue = queueName;
string cmd = "\"" + Settings.FusionProExe + "\" \"" + dataFilePath + "\" \""
+ message.DiffFilePath + "\" \"" +
(isProof ? message.ProofConfigFilePath : message.PrintConfigFilePath) + "\" \""
+ pdfFilePath + "\"";
vdpQueueJob.CommandLine = cmd;
client.ConnectRemote(Settings.FusionProServer, Settings.FusionProUser, Settings.FusionProPassword, Settings.FusionProTimeout);
client.SubmitJob(vdpQueueJob, Settings.FusionProTimeout, true);
return pdfFilePath;

Unable to generate file from ASP.NET with inkscape

I have an ASP.NET application on my local machine that works. This application takes an SVG file and creates a PNG from it using inkscape. I have tried to migrate that application to my production server. Oddly, the png creation is not working. The really strange part is, an Exception is not being thrown either. I have taken the command line parameters that are being created and copied and pasted them into the command line environment and they work. For instance, here is the line:
inkscape.exe -f "C:\inetpub\wwwroot\MyTest\sample.svg" -e "C:\inetpub\wwwroot\MyTest\sample.png"
I thought it was something simple, so I extracted the code into a sample web project. This project just converts a .svg to a .png. Once again, it worked in my local environment, but not in the production environment. Here is the code:
protected void executeButton_Click(object sender, EventArgs e)
{
try
{
string sourceFile = Server.MapPath("svg") + "\\" + ConfigurationManager.AppSettings["sourceFile"];
string targetFile = Server.MapPath("png") + "\\" + ConfigurationManager.AppSettings["targetFile"];
string args = "-f \"" + sourceFile + "\" -e \"" + targetFile + "\" -w100 -h40";
string inkscape = ConfigurationManager.AppSettings["inkscapeExe"];
// Generate the png via inkscape
ProcessStartInfo inkscapeInfo = new ProcessStartInfo(inkscape, args);
Process inkscape = Process.Start(inkscapeInfo);
inkscape.WaitForExit(5000);
runLiteral.Text = "Success!<br />" + args;
}
catch (Exception ex)
{
runLiteral.Text = ex.GetType().FullName + "<br />" + ex.Message + "<br />" + ex.StackTrace;
}
}
Can someone tell me what I'm doing wrong?
Thank you!
A couple things to check:
Make sure that the application pool identity for the web application (found in IIS, usually NetworkService) has permissions to execute inkscape.exe
If that is fine, check to make sure that the directory grants Modify permissions to the apppool identity on the directory(ies) you are writing the PNG to ("C:\inetpub\wwwroot\MyTest")
Alternatively, you can use impersonation to run the executable under a specific Windows account.

Categories

Resources