Cannot get a certificate file from application running at server - c#

I have an application written in C# MVC 4, which will run on server, that has one certificate inside the project, in the App_Data folder. I need to get this certificate file to access a Web Service. The server is a Windows Server 2012, using iis7.
The code runs as expected locally, but it does not work on the server. There I receive the message "The system cannot find the file specified". But this file IS there (I return the content of this directory and the previous one, getting them on the browser's console).
I tried to rename the certificate from .pfx to .pcertx (a random one) and doesn't work on the server again, although it works locally.
Here's the code I'm using to try to get this file:
public string getCertificado()
{
string path = string.Empty;
try
{
path = HttpContext.Current.Server.MapPath(#"~\App_Data\CERTIFICATE.pcertx");
Byte[] rawCert = File.ReadAllBytes(path);
String certificado = Convert.ToBase64String(rawCert);
_X509Cert.Import(Convert.FromBase64String(certificado), "PASSWORD", X509KeyStorageFlags.PersistKeySet);
client.AddCerts(new X509Certificate[] { _X509Cert });
return string.Empty;
}
catch (Exception ex)
{
// In case of error, list the content of the current directory and the previous
string[] filePaths = Directory.GetFiles(HttpContext.Current.Server.MapPath(#"~\App_Data"));
string pastaAnterior = Path.GetFullPath(Path.Combine(HttpContext.Current.Server.MapPath(#"~\App_Data"), #"..\"));
string[] filePathsAnt = Directory.GetFiles(pastaAnterior);
return "Cannot get certificate." + ex.Message + "; " + ex.InnerException + "; Path: " + path + "; Folder content: " + string.Join("\n",filePaths) + "; Previous folder content" + string.Join("\n",filePathsAnt);
}
}
This is what I get from the browser's console:
"Não foi possível obter nenhum certificado.
The system cannot find the file specified.
Path: C:\Unisys\Management\Applications\sicopplustest\App_Data\CERTIFICATE.pcertx;
Caminho pasta:
C:\Unisys\Management\Applications\sicopplustest\App_Data\CERTIFICATE.pcertx
C:\Unisys\Management\Applications\sicopplustest\App_Data\DynamicAspx.xsl;
Caminho pasta anteriorC:\Unisys\Management\Applications\sicopplustest\ApplicationInfo.Debug.xml
C:\Unisys\Management\Applications\sicopplustest\ApplicationInfo.Release.xml
C:\Unisys\Management\Applications\sicopplustest\ApplicationInfo.xml
..."
If I got the certificate properly, no message would be sent.
I think it may be related to security, but how can I fix it? I don't know how to procede with this situation.

Related

c# adobe acrobat SDK: file is still locked after SDK quit

I'm working with C# and adobe acrobat SDK.
When the program throws an error due to the pdf already being compressed I want to move the pdf.
However, C# complains that the file is being used by another process and I know it has to do with the SDK and not another program.
After some debugging I found out that compressPDFOperation.Execute is the culprit.
How can I close it so that I can move the file?
try {
// Initial setup, create credentials instance.
Console.WriteLine(".json: " + Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json");
Credentials credentials = Credentials.ServiceAccountCredentialsBuilder()
.FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json")
.Build();
// Create an ExecutionContext using credentials and create a new operation instance.
ExecutionContext executionContext = ExecutionContext.Create(credentials);
CompressPDFOperation compressPDFOperation = CompressPDFOperation.CreateNew();
// Set operation input from a source file.
FileRef sourceFileRef = FileRef.CreateFromLocalFile(directory + #"\" + pdfname);
compressPDFOperation.SetInput(sourceFileRef);
// Execute the operation.
FileRef result = compressPDFOperation.Execute(executionContext);
// Save the result to the specified location.
//if pdf is part of a group, the group directory name will be stored in fileGroupDirectory
string fileGroupDirectory = directory.Replace(sourceDir, "");
result.SaveAs(finishedDir + fileGroupDirectory + pdfname);
}
catch (ServiceApiException ex)
{
Console.WriteLine("Exception encountered while executing operation", ex.Message);
if (ex.Message.Contains("The input file is already compressed"))
{
File.Move(file, finishedDir + fileGroupDirectory + fileName);
}
}
I've found a solution , it's not best practice but I don't know an other way to do it.
I've declared all the variables used to execute the compression (sourceFileRef, compressPdfOperation, ...) before the try catch statement and after result.SaveAs(...) I set those variables to null and run the garbage collection.
compressPDFOperation = null;
result = null;
sourceFileRef = null;
executionContext = null;
credentials = null;
GC.Collect();

C# Windows Service Not Compressing Folder Correctly

Im currently building a Windows service that will be used to create backups of logs. Currently, the logs are stored at the path E:\Logs and intent is to copy the contents, timestamp their new folder and compress it. After this, you should have E:\Logs and E:\Logs_[Timestamp].zip. The zip will be moved to C:\Backups\ for later processing. Currently, I am using the following to try and zip the log folder:
var logDirectory = "E://Logs";
var timeStamp = DateTime.Now.ToString("yyyyMMddHHmm");
var zippedFolder = logDirectory + "_" + timeStamp + ".zip";
System.IO.Compression.ZipFile.CreateFromDirectory(logDirectory, zippedFolder);
While this appears to create a zip folder, I get the error Windows cannot open the folder. The Compressed (zipped) Folder E:\Logs_201805161035.zip is invalid.
To address any troubleshooting issues, the service is running with an AD account that has a sufficient permission level to perform administrative tasks. Another thing to consider is that the service kicks off when its FileSystemWatcher detects a new zip folder in the path C:\Aggregate. Since there are many zip folders that are added to C:\Aggregate at once, the FileSystemWatcher creates a new Task for each zip found. You can see how this works in the following:
private void FileFoundInDrops(object sender, FileSystemEventArgs e)
{
var aggregatePath = new DirectoryInfo("C://Aggregate");
if (e.FullPath.Contains(".zip"))
{
Task task = Task.Factory.StartNew(() =>
{
try
{
var logDirectory = "E://Logs";
var timeStamp = DateTime.Now.ToString("yyyyMMddHHmm");
var zippedFolder = logDirectory + "_" + timeStamp + ".zip";
ZipFile.CreateFromDirectory(logDirectory, zippedFolder);
}
catch (Exception ex)
{
Log.WriteLine(System.DateTime.Now.ToString() + " - ERROR: " + ex);
}
});
task.Dispose();
}
}
How can I get around the error I am receiving? Any help would be appreciated!

while copying files using File.copy i get error

when i run file.copy to copy files in network path for large files i get the below error but in back end files are getting copied twice.
This site can’t be reached The webpage at http://******************* might be temporarily down or it may have moved permanently to a new web address. ERR_INVALID_HANDLE
foreach (GridViewRow row in grdAppDetails.Rows)
{
Label lblPublishPath = (Label)row.FindControl("lblPublishPath");
Label lblBackupPath = (Label)row.FindControl("lblBackupPath");
string BackupPath = lblBackupPath.Text + "\\" + drpApplication.SelectedValue.ToString() + "_" + DateTime.Now.ToString("yyyyMMdd");
DirectoryCopy(lblPublishPath.Text, BackupPath, true);
DirectoryCopy(txtFolderUpload.Text, lblPublishPath.Text, true);
deploymentdata.AddAppLogDetails(drpApplication.SelectedValue.ToString(), drpEnv.SelectedValue.ToString(), lblUserName.Text, DateTime.Now, txtFolderUpload.Text, BackupPath, lblPublishPath.Text, txtComments.Text, filenames);
}
try to :
1- ping the destination to be sure that you have access.
2- once the ping succeed , try to check if you can write file from your machine
you can do it like this : Properties-->share --> and add your user if you don't have access to the directory

System.IO.File.Move error - Could not find a part of the path

I have a sync software, which loads CSV files from "Incoming" folder, processes them and then moves them to the "Archive" folder.
Today, I saw the following error with this sync software:
[23/06/2014 00:06:04 AM] : Failed to move file from
D:\IBI_ORDER_IMPORTER_FTP_SERVER\Template3\Fifty &
Dean\Incoming\5A040K___d6f1ca45937b4ceb98d29d0db4601bf4.csv to
D:\IBI_ORDER_IMPORTER_FTP_SERVER\Template3\Fifty &
Dean\Archive\5A040K___d6f1ca45937b4ceb98d29d0db4601bf4.csv - Could not
find a part of the path.
Here's a snippet taken out of the sync software, where the file is processed and moved:
public static void ProcessSingleUserFile(Int32 TemplateId, String ImportedBy, String FilePath)
{
// Always Rename File To Avoid Conflict
string FileName = Path.GetFileNameWithoutExtension(FilePath);
String NewFilePath = FilePath.Replace(FileName, Utils.RandomString() + "___" + FileName);
File.Move(FilePath, NewFilePath);
FilePath = NewFilePath;
// Log
SyncUtils.ConsoleLog(String.Format("Processing [ {0} as {1} ] By [ {2} ] On Template [ #{3} ]",
FileName + ".csv",
Path.GetFileName(FilePath),
ImportedBy,
TemplateId));
// Init
List<OrderDraft> myOrderDrafts = new List<OrderDraft>();
// Parsed Based On Template Id
if (TemplateId == Settings.Default.Multi_Order_Template_Id)
{
// Try Parse File
myOrderDrafts = Utils.ParseMultiImportFile(TemplateId, ImportedBy, FilePath, true);
}
else
{
// Try Parse File
myOrderDrafts.Add(Utils.ParseImportFile(TemplateId, ImportedBy, FilePath, true));
}
// Process Orders
foreach (OrderDraft myOrderDraft in myOrderDrafts)
{
/* code snipped */
}
// Archive File
File.Move(FilePath, FilePath.Replace("Incoming", "Archive"));
}
Any idea what this error means? and how to circumvent it?
I wrote a cut down version of the above to test this in a controlled environment and I am not getting the error with this code:
static void Main(string[] args)
{
try
{
string baseDir = #"C:\Users\Administrator\Desktop\FTP_SERVER\Template3\Fifty & Dean\Incoming\";
string[] filePaths = Directory.GetFiles(baseDir, "*.csv");
foreach (string filePath in filePaths)
{
// do some work here ...
// move file
string newFilePath = filePath.Replace("Incoming", "Archive");
File.Move(filePath, newFilePath);
Console.WriteLine("File successfully moved");
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Console.ReadKey();
}
You need to include the checks to make sure that the paths exist at runtime and check the output, something very simple like:
if(!Directory.Exists(Path.GetDirectoryName(filePath)))
{
Console.WriteLine("filePath does not exist: " + filePath);
}
if(!Directory.Exists(Path.GetDirectoryName(newFilePath)))
{
Console.WriteLine("newFilePath does not exist: " + newFilePath);
}
File.Move(filePath, newFilePath);
The reason I am suggesting this method is due to a possibility that the paths momentarily become available or not under the multi-tasking OSs depending on a multitude of factors: network connectivity, permissions (pushed down by GPO at any time), firewall rules, AV exclusions getting blown away etc. Even running low on CPU or RAM may create issues. In short, you never know what exactly occurred when your code was running if you are only checking the paths availability after the fact.
Or if your issue is intermittent, you can try and catch the error and write information to some sort of a log similarly to below:
try
{
File.Move(filePath, newFilePath);
}
catch(Exception ex)
{
if(!Directory.Exists(Path.GetDirectoryName(filePath)))
{
Console.WriteLine("filePath does not exist: " + filePath);
}
if(!Directory.Exists(Path.GetDirectoryName(newFilePath)))
{
Console.WriteLine("newFilePath does not exist: " + newFilePath);
}
}
"Could not find a part of the path" exception could also thrown from File.Move if argument used was longer than MAX_PATH (260) in .NET Framework.
So I prepend the path I used with long path syntax before passing to File.Move and it worked.
// Prepend long file path support
if( !packageFile.StartsWith( #"\\?\" ) )
packageFile = #"\\?\" + packageFile;
See:
How to deal with files with a name longer than 259 characters?
I have this
Could not find a part of the path
happened to me when I
File.Move(mapfile_path , Path.Combine(newPath, mapFile));
. After some testing, I find out our server administrator has blocked any user application from writing to that directory in that [newPath]!
So, right click on that directory to observe the rights matrix on Security tab to see anything that would block you.
Another cause of DirectoryNotFoundException "could not find a part of the path" thrown by File.Move can be spaces at the end of the directory name. Consider the following code:
string destinationPath = "C:\\Folder1 "; //note the space on the end
string destinationFileNameAndPath = Path.Combine(destinationPath, "file.txt");
if (!Directory.Exists(destinationPath))
Directory.CreateDirectory(destinationPath);
File.Move(sourceFileNameAndPath, destinationFileNameAndPath);
You may expect this code to succeed, since it creates the destination directory if it doesn't already exist, but Directory.CreateDirectory seems to trim the extra space on the end of the directory name, whereas File.Move does not and gives the above exception.
In this circumstance, you can workaround this by trimming the extra space yourself, e.g. (depending on how you load your path variable, the below is obviously overkill for a hard-coded string)
string destinationPath = "C:\\Folder1 ".Trim();

The remote server returned an error: (405) Method Allowed

I know that this is a common problem facing over, but am getting this this problem with a different scenario.
am going to explain scenario here
I created a two different projects in a solution. The image containing folder that i want to use for save, i-e upload is outside of these above projects but under same solution.
Actually i created virtual directly (My File Server) on IIS server of this folder
here is my code.
private void SaveData()
{
string filename = Path.GetFileName(ImageUpload.PostedFile.FileName);
string servpath = Server.MapPath(ConfigurationManager.AppSettings["TempFolder"]);
ImageUpload.SaveAs(servpath + filename);
string remoteServerPath = ConfigurationManager.AppSettings["ProductImagesPath"] + filename;
try
{
WebClient client = new WebClient();
client.UploadFile(remoteServerPath, servpath + filename);
}
catch (Exception ex)
{
throw ex;
}
objProductsCustom.ProductName = txtProductName.Text;
objProductsCustom.ProductDiscription = txtAddDiscription.Text;
objProductsCustom.ProductPrice = txtPrice.Text;
objProductsCustom.Quantity = txtQuantity.Text;
objProductsCustom.ImagePath = "servpath" + filename;
int productID = objProductsManager.CreatProduct(objProductsCustom);
}
Where on try-catch, I found "The remote server returned an error: (405) Method Allowed." error. I am stuck.
EDIT
This is the remoteserverpath :
http://localhost/ProductImages/untitled.bmp
And this is the file which i am uploading to remoteserverpath:
C:\Documents and Settings\saltaf\My Documents\Visual Studio 2010\Projects \OnlineShoppingSystem\OnlineShoppingSiteAdminPanel\Temp\Images\untitled.bmp
And this is my call:
webclient.UploadFile(http://localhost/ProductImages/untitled.bmp,C:\Documents and Settings\saltaf\My Documents\Visual Studio 2010\Projects\OnlineShoppingSystem\OnlineShoppingSiteAdminPanel\Temp\Images\untitled.bmp)
Have you tried checking the permissions for the folder which you are saving the file into? It's supposed to include the 'IIS_IUSRS' profile there (which should also have the WRITE permission to the target folder).
Hope this helps.

Categories