C#, iis7 web server not writing log files - c#

I'm trying to get my web server to write logs to a txt file on the server. It should be simple and it is working fine on my development machine but it doesn't on the server.
I have followed he advice in this: IIS7 Permissions Overview - ApplicationPoolIdentity
But it still won't write. the path is correct and it should have the proper permissions after following the above link.
my code for writing the file is:
private void Logger(String lines)
{
String fileName = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + "_Logs.txt";
try
{
System.IO.StreamWriter file = new System.IO.StreamWriter("C:/Web_Srvice_Logs/" + fileName, true);
file.WriteLine(lines + " " + DateTime.Now.ToString());
file.Close();
}
catch (Exception) { }
any Ideas?

Catch the exception and check the value. My guess is that the App Pool user does not have rights to write to that directory (I know you said you checked it) and/or that directory does not exist. The error message you are getting will help diagnose it.
You could always set the app pool to an admin user to test if it is a permission problem.

Related

Some times PDF files get corrupted after File Upload C#

I am trying to upload PDF files. Only sometimes uploaded file gets corrupt. When I open that file on Adobe or browser. its says Insufficient data for an images
This problem is not for all the uploads. When I tried to upload the same file again its works perfectly.
I am not able to replicate the issue so that I can know why this type of issue occurring
I am using below code to save the file
FileUpload upload = GridView1.Rows[index].FindControl("FileUpload1") as FileUpload;
if (upload.HasFile)
{
string nameoffile = upload.FileName;
Random ran = new Random();
int forReference = ran.Next();
string[] strfileArray = nameoffile.Split('.');
nameoffile = strfileArray[0] + "" + forReference + ".pdf";
upload.SaveAs(path + "/" + nameoffile);
}
else
{
upload.SaveAs(path + "/" + nameoffile);
}
Note: We are running this appliaction on Azure VM. This code was works without any issue on previous server. since we migrated to Azure
We had hosted application on C drive of azure VM. After Changing application to secondary storage i.e. D drive problem got resolved

Exception of type 'Tamir.SharpSsh.jsch.SftpException' was thrown

Im able to connect to the sftp server
am able to get the list of files in "pickup" directory.
But I can't download any of those files.
Here is my code:
try
{
sftp.Get(txtRemotePath.Text + txtFixedFileName.Text, txtLocalPath.Text + txtFixedFileName.Text);
//example:
//txtRemotePath.Text + txtFixedFileName.Text = "/pickup/temp.txt";
//txtLocalPath.Text + txtFixedFileName.Text = #"C:\Users\...\temp.txt"
}
catch (Exception ex)
{
lblError.Text += "\n" + ex.Message;
}
I tried modifiying the local and remote paths switching betwen slashes "/" and back-slashes "\", removing/addding starting slashes in remote path..
unfortunatly same error is generated:
Exception of type 'Tamir.SharpSsh.jsch.SftpException' was thrown
check the sftp server security to allow you in through specific port
It was The sftp server security that didn't allow me to download files!
I received the same error when uploading a file. I realised though that I did not have permission to the root directory. When using a folder with the correct permissions I could upload the file successfully.

Directory.Move(): Access to Path is Denied

I'm writing this Windows Form Application in Visual Studio 2010 using C#.
There is a Execute button on the form, the user will hit the button, the program will generate some files and are stored in the Output folder (which is created by the program using Directory.CreateDirectory())
I want to create an Archive folder to save the output files from previous runs.
In the beginning of each run, I try to move the existing Output folder to the Archive folder, then create a new Output folder. Below is the function I ran to move directory.
static void moveToArchive()
{
if (!Directory.Exists("Archive")) Directory.CreateDirectory("Archive");
string timestamp = DateTime.Now.ToString("yyyyMMddHHmms");
try
{
Directory.Move("Output", "Archive\\" + timestamp);
}
catch(Exception e)
{
Console.WriteLine("Can not move folder: " + e.Message);
}
}
The problem I ran into confuses me a lot...
There are some times that I can successfully move the Output folder to archive, but sometimes it fails.
The error message I got from catching the exception is Access to path 'Output' is denied.
I have checked that all the files in the Output folder are not in use. I don't understand how access is denied sometimes and not all the times.
Can someone explain to me and show me how to resolve the problem?
--Edit--
After HansPassant comment, I modified the function a little to get the current directory and use the full path. However, I'm still having the same issue.
The function now looks like this:
static void moveToArchive()
{
string currentDir = Environment.CurrentDirectory;
Console.WriteLine("Current Directory = " + currentDir);
if (!Directory.Exists(currentDir + "\\Archive")) Directory.CreateDirectory(currentDir + "\\Archive");
string timestamp = DateTime.Now.ToString("yyyyMMddHHmms");
try
{
Directory.Move(currentDir + "\\Output", currentDir + "\\Archive\\" + timestamp);
}
catch(Exception e)
{
Console.WriteLine("Can not move folder: " + e.Message);
}
}
I printed out the current directory and it is just as what I was expecting, and I'm still having trouble using full path. Access to path 'C:\Users\Me\Desktop\FormApp\Output' is denied.
--Edit--
Thank you everyone for answering and commenting.
I think some of you miss this part so I'm going stress it a bit more.
The Directory.Move() sometimes work and sometimes fails.
When the function succeed, there was no problem. Output folder is moved to Archive
When the function fails, the exception message I got was Access to path denied.
Thank you all for the replies and help. I have figured out what the issue was.
It is because there was a file that's not completely closed.
I was checking the files that were generated, and missed the files the program was reading from.
All files that were generated were closed completely. It was one file I used StreamReader to open but didn't close. I modified the code and am now not having problem, so I figure that's were the issue was.
Thanks for all the comments and answers, that definitely help me with thinking and figuring out the problem.
See http://windowsxp.mvps.org/processlock.htm
Sometimes, you try to move or delete a file or folder and receive access violation or file in use - errors. To successfully delete a file, you will need to identify the process which has locked the file. You need to exit the process first and then delete the particular file. To know which process has locked a file, you may use one of the methods discussed in this article.
Using Process Explorer - download from http://download.sysinternals.com/files/ProcessExplorer.zip
Process Explorer shows you information about which handles and DLLs processes have opened or loaded.
Download Process Explorer from Microsoft site and run the program.
Click the Find menu, and choose Find Handle or DLL...
Type the file name (name of the file which is locked by some process.)
After typing the search phrase, click the Search button
You should see the list of applications which are accessing the file.
I bumped on the same problem recently. Using PE I'd figured that only process using that particular directory was explorer.exe. I'd opened few windows with explorer, one pointing to parent directory of one that I was about to move.
It appeared, that after I visited that sub-folder and then returned (even to root level!) the handle was still being kept by explorer, so C# was not able to modify it in any way (changing flags, attributes etc.).
I had to kill that explorer window in order to made C# operate properly.
File.SetAttributes(Application.dataPath + "/script", FileAttributes.Normal);
Directory.Move(Application.dataPath + "/script", Application.dataPath + "/../script");
This fixed my problem.
Try this:
If this does not solve, maybe check/change the antivirus, or the some other program is locking some file in or the folder.
static object moveLocker = new object();
static void moveToArchive()
{
lock (moveLocker)
{
System.Threading.Thread.Sleep(2000); // Give sometime to ensure all file are closed.
//Environment.CurrentDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
string applicationPath = System.AppDomain.CurrentDomain.BaseDirectory;
string archiveBaseDirectoryPath = System.IO.Path.Combine(applicationPath, "Archive");
if (!Directory.Exists(archiveBaseDirectoryPath)) Directory.CreateDirectory(archiveBaseDirectoryPath);
String timestamp = DateTime.Now.ToString("yyyyMMddHHmms");
String outputDirectory = System.IO.Path.Combine(Environment.CurrentDirectory, "Output");
String destinationTS = System.IO.Path.Combine(archiveBaseDirectoryPath, timestamp);
try
{
Directory.Move(outputDirectory, destinationTS);
}
catch (Exception ex)
{
Console.WriteLine("Can not move folder " + outputDirectory + " to: " + destinationTS + "\n" + ex.Message);
}
}
}
I had the same problem, it failed sometimes but not all the time. I thought I'd wrap it in a Try Catch block and present the user with an Access Denied message and once I wrapped it in the Try Catch block it stopped failing. I can't explain why.
If existingFile.FileName <> newFileName Then
Dim dir As New IO.DirectoryInfo(existingFile.FilePath)
Dim path As String = System.IO.Path.GetDirectoryName(dir.FullName)
newFileName = path & "\" & newFileName
File.SetAttributes(existingFile.FilePath, FileAttributes.Normal)
Try
IO.File.Move(existingFile.FilePath, newFileName)
Catch ex As Exception
End Try
End If
I had a similar problem. Renamed many directories in a loop when following the certain template. From time to time the program crashed on different directories. It helped to add a sleep thread before Directory.Move. I need to create some delay.
But it slows down the copying process.
foreach (var currentFullDirPath in Directory.GetDirectories(startTargetFullDirectory, "*", SearchOption.AllDirectories))
{
var shortCurrentFolderName = new DirectoryInfo(currentFullDirPath).Name.ToLower();
if (shortCurrentFolderName.Contains(shortSourceDirectoryName))
{
// Add Thread.Sleep(1000);
Thread.Sleep(1000);
var newFullDirName = ...;
Directory.Move(currentFullDirPath, newFullDirName);
}
}

System.UnauthorizedAccessException while creating a file

I was trying to write a code so that I could log the error messages. I am trying to name the file with the date and would like to create a new log file for each day. After going through a little look around, I came with the following code...
class ErrorLog
{
public void WriteErrorToFile(string error)
{
//http://msdn.microsoft.com/en-us/library/aa326721.aspx refer for more info
string fileName = DateTime.Now.ToString("dd-MM-yy", DateTimeFormatInfo.InvariantInfo);
//# symbol helps to ignore that escape sequence thing
string filePath = #"c:\users\MyName\mydocuments\visual studio 2012\projects\training\" +
#"discussionboard\ErrorLog\" + fileName + ".txt";
if (File.Exists(filePath))
{
// File.SetAttributes(filePath, FileAttributes.Normal);
File.WriteAllText(filePath, error);
}
else
{
Directory.CreateDirectory(filePath);
// File.SetAttributes(filePath, FileAttributes.Normal)
//Throws unauthorized access exception
RemoveReadOnlyAccess(filePath);
File.WriteAllText(filePath, error);
}
}
public static void RemoveReadOnlyAccess(string pathToFile)
{
FileInfo myFileInfo = new FileInfo(pathToFile);
myFileInfo.IsReadOnly = false;
myFileInfo.Refresh();
}
/*Exception thrown:
* UnAuthorizedAccessException was unhandled.
* Access to the path 'c:\users\anish\mydocuments\visual studio 2012\
* projects\training\discussionboard\ErrorLog\04\12\2013.txt' is denied.
*/
}
I found a forum that has discussed about a similar problem but using
File.SetAttrributes(filePath, FileAttributes.Normal) did not help neither did the RemoveReadOnlyAccess (included in the code above). When I check the properties of the folder, it has read only marked but even when I tick that off it comes back again. I checked the permissions on the folder and except for the special permission, which I was not able to change, everything is allowed.
Any suggestion on how I should proceed would be appreciated.
Why is access to the path denied? the link discusses about a similar problem, but I wasn't able to get my thing working with suggestions listed there.
Thanks for taking time to look at this.
Your path is strange : "My documents" directory must be "C:\Users\MyName\Documents\"
You can use Environment in order to correct it easily :
String myDocumentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Note that it will acces to "My documents" folder of the user that running your exe.
Second error, CreateDirectory must have a path in argument, not a file. using like you do will create a sub-directory with the file name. So you can't create a file with this name !
Try this :
String fileName = DateTime.Now.ToString("d", DateTimeFormatInfo.InvariantInfo);
String filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
+ #"\visual studio 2012\projects\training\discussionboard\ErrorLog\";
String fileFullName = filePath + fileName + ".txt";
if (File.Exists(fileFullName ))
{
File.WriteAllText(fileFullName , error);
}
else
{
Directory.CreateDirectory(filePath);
[...]
}
}
Some possible reasons:
your app is not running under account which is allowed to access that path/file
the file is being locked for writing (or maybe reading too) by some other process
The first situation could be solved by checking under which account the process is running and verifying that the account has the appropriate rights.
The other situation can be solved by checking if any other process is locking the file (e.g. use tools like 'WhosLocking' or 'ProcessExplorer'
I had to run my app as an administrator in order to write to protected folders in c:. For example if debugging your app in visual studio make sure to right click on "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe" and choose "Run As Administrator". Then open your solution from there. My app was trying to write to the root of c:\
Check your antivirus, it might be blocking the file creation.

Anyone know why I can't access the winevt folder programmatically in C#?

I've been trying to get into the 'C:\Windows\System32\winevt\Logs' folder programmatically using C# so I can copy the event log files to a backup directory and then clear the event logs as a part of a daily backup apparatus, but I don't seem to be able to get access to this directory.
I've tried changing the application manifest to run under administrator ( ) which gives me the UAC prompt when I execute the program and I've even gone as far as to spawn a shell under NT AUHORITY\SYSTEM identity to execute the code but it still says it's an invalid path, even though I can manually go into the directory under both administrative shell and the SYSTEM shell.
I've isolated it to just not being able to go into the winevt dir.
I use this code to see if I can access the directory.
Environment.CurrentDirectory = System.Environment.SystemDirectory + #"\winevt\";
only to receive
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Windows\system32\winevt\'.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.SetCurrentDirectory(String path)
at System.Environment.set_CurrentDirectory(String value)
at dev_EventLog.Program.Main(String[] args) in D:\SourceCodes\dev_EventLog\dev_EventLog\Program.cs:line 30
I've tried many different ways to specify the directory but it's all the same, and I've also tried different subfolder of System32 and of the 10 or so I tried winevt is the only one to act like this.
This has been driving me nuts, anyone know why this isn't working under C# or am I forced to use VBScript to do this, since the following VBScript code works to copy the event log file.
dim filesys
set filesys=CreateObject("Scripting.FileSystemObject")
filesys.CopyFile "C:\Windows\System32\winevt\Logs\Application.evtx", "C:\rusl\Application.evtx"
Is your application running as a 32-bit application on a 64-bit version of Windows? If so, any access to %windir%\System32 is redirected to %windir%\SystemWOW64 (where there is no winevt directory).
If you use %windir%\Sysnative\winevt you should be able to access it.
Here is the code that I have that works now after I changed system32 to sysnative as per John Rasch suggestion.
string LogFileDirectory = #"C:\Windows\Sysnative\winevt\Logs\";
string LogFileExtension = ".evtx";
string Date = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString();
string BackupDir = #"C:\Backups\" + Date + "\\";
Directory.CreateDirectory(BackupDir);
foreach (EventLog log in EventLog.GetEventLogs())
{
string source = LogFileDirectory + log.Log + LogFileExtension;
string dest = BackupDir + log.Log + LogFileExtension;
try
{
File.Copy(source, dest);
}
catch (Exception e)
{
Console.WriteLine("Error occured :" + e.Message);
Console.WriteLine(e);
}
finally
{
if (!File.Exists(dest))
{
Console.WriteLine("Backup Failed for " + log.Log);
}
else
{
Console.WriteLine("Backup Successful for " + log.Log);
//log.Clear(); // Commented out during development
}
}
}

Categories

Resources