I tired to write in loop virus signatures to files.
My code :
for (int i = 0; i < liczba; i++)
{
int current = i + 1;
string xxx = w.DownloadString("xxx(hidden)");
if (xxx != "0")
{
string[] wirus = xxx.Split("|||".ToCharArray());
string s2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "_RDTSignatures", "base000" + current.ToString() + ".rdtsignature");
File.Create(s2);
StreamWriter sss = new StreamWriter(s2); //that's crash line
sss.WriteLine("hidden");
sss.WriteLine(wirus[0]);
sss.WriteLine(wirus[1]);
sss.Close();
File.Encrypt(s2);
}
}
w is a WebClient object. Error callback :
System.IO.IOException: Process cannot access file : „C:\Users\Pluse Konto\Documents\Visual Studio 2010\Projects\Radzik Diagnostic Tool\Radzik Diagnostic Tool\bin\Debug\_RDTSignatures\base0001.rdtsignature”, because it is used by other process.
w System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
w System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
w System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
w System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
w System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
w System.IO.StreamWriter..ctor(String path)
w Radzik_Diagnostic_Tool.Updates.timer1_Tick(Object sender, EventArgs e) w C:\Users\Pluse Konto\documents\visual studio 2010\Projects\Radzik Diagnostic Tool\Radzik Diagnostic Tool\Updates.cs:line 69
w System.Windows.Forms.Timer.OnTick(EventArgs e)
w System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)
w System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
I don't know what is the reason of that error. No process is using my files, except my main thread, of course.
PS File base0001.rdtsignature has been created, but is empty.
File.Create returns the open FileStream, So when you create new StreamWriter it tries to access the file which is already opened in your process with File.Create results in IOException
Try this
using (StreamWriter sss = new StreamWriter(File.Create(s2)))
{
//Make use of sss
}
Using statement ensures underlying stream of StreamWriter is closed when control exits Using. So no need to call sss.Close(); manually. using statement does it for you even when there is exception thrown.
You don't close the file created by File.Create(s2);.
Try using( File.Create(s2) ); or File.Create(s2).Close();
Just comment out:
File.Create(s2);
The problem is that File.Create(s2) returns a FileStream which leaves the file open. You are then trying to create a second stream to open the file for writing again which is why you get the error that the file is already open.
If you always want to create a new file, change your line that creates the StreamWriter to read:
StreamWriter sss = new StreamWriter(s2, false);
That will make it not append to an existing file but rather overwrite it.
Instead of:
File.Create(s2);
StreamWriter sss = new StreamWriter(s2); //that's crash line
Use:
StreamWriter sss = File.CreateText(s2);
Related
I am trying to write a windows forms app that will write logs to a .txt file in:
Documents/subfolder/name.txt
I am able to create a the subfolder directory using
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string dirPath = Path.Combine(documentsPath, appFolderName, logFolderSubpath);
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
string fileName = "log" + DateTime.Now.ToString("_yyyy-MM-dd_hh-mm-ss") + ".txt";
string path = Path.Combine(dirPath, fileName);
but when I try to create a StreamWriter:
StreamWriter writer = new StreamWriter(Path.Combine(path, filename));
where filename is just a name of a .txt file, I get the exception:
System.UnauthorizedAccessException
HResult=0x80070005
Message=Access to the path 'C:\Users\milos_qhhen\Documents\DNDice\logs\log_2021-04-30_10-30-33.txt' is denied.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
at System.IO.StreamWriter..ctor(String path)
at Character_Sheet.Logger..ctor() in D:\Milos\DND\Character Sheet\Character Sheet\Logger.cs:line 35
at Character_Sheet.MainForm.MainForm_Load(Object sender, EventArgs e) in D:\Milos\DND\Character Sheet\Character Sheet\MainForm.cs:line 57
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Form.OnCreateControl()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmShowWindow(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
This exception was originally thrown at this call stack:
[External Code]
Character_Sheet.Logger.Logger() in Logger.cs
Character_Sheet.MainForm.MainForm_Load(object, System.EventArgs) in MainForm.cs
[External Code]
I am trying to make my app write log files into the Documents directory because this is a program that will be used by multiple people and I want a constant place where I can write the logs to. So I need my program to be able to create the directory, to create the file inside it, and then write into that file! I would prefer not to do this in the same directory where the .exe is.
Maybe the user you are using doesn't have write permission on that folder. Try to add write permission for you user or simply run the VS as administrator. It should work
I had this issue when running a .net console app on a Linux machine. the issues was that the user didn't have execute permissions to the folder
this command solved it for me
sudo chmod -R a+rwx ##folder path##
I have and ASP Web API and I'm trying to return a file from a call there.
On my server I keep getting the error:
System.UnauthorizedAccessException: Access to the path
'E:\Data\Docs\specific\document.pdf' is denied. at
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess
access, Int32 rights, Boolean useRights, FileShare share, Int32
bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String
msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess
access, FileShare share, Int32 bufferSize, FileOptions options, String
msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String
path, FileMode mode) at
GIS.Backend.Assets.BLL.Document.GetByUrl(String url) at
GIS.Backend.Assets.WebApi.Controllers.DocumentController.Get(String
url)
I'm guessing this is where it goes wrong:
string documentenPath = System.Web.Configuration.WebConfigurationManager.AppSettings["DocumentenDir"].ToString();
string fullUrl = documentenPath + url;
Stream file = new FileStream(fullUrl, FileMode.Open);
return file;
I have set IIS_IUSRS to have read access to the 'Docs' folder, so it should be able to read right?
open the Stream with the FileAccess.Read flag
FileStream fs = new FileStream(fullUrl, FileMode.Open, FileAccess.Read);
File.Open also needs a FileAccess.Read or a System.UnauthorizedAccessException exception will be thrown by the server
FileStream fileStream = System.IO.File.Open(fullUrl, FileMode.Open, FileAccess.Read);
Guys can some one tell me why i have such error ....
2013-08-11 18:44:28 - NPMessage: DEBUG: Dispatching a RPCStorageWriteUserFileMessage
2013-08-11 18:44:28 - RPCStorageWriteUserFileMessage: INFO: Got a request for writing 8192 bytes to file iw4.stat for user alhpons.
2013-08-11 18:44:28 - ProfileData: INFO: Handling profile update request for alhpons
2013-08-11 18:44:28 - ProfileData: ERROR: Exception: System.IO.IOException: The process cannot access the file 'D:\IW4M\NpServer\data\priv2\00\000\alhpons\iw4.stat' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.IO.File.ReadAllBytes(String path)
at NPx.ProfileData.Handle(UpdateRequest request)
at NPx.ProfileData.Run()
Edit:
i use my App on windows server 2008 and some files need to read / write permission for my application but i have such error so i need to fix that problem and my source is:
public override void Process(NPHandler client)
{
var fileName = Message.fileName;
var fileData = Message.fileData;
var npid = (long)Message.npid;
var fsFile = StorageUtils.GetFilename(fileName, npid);
_client = client;
_fileName = fileName;
_npid = npid;
if (!client.Authenticated)
{
ReplyWithError(1);
return;
}
if (client.NPID != (long)npid)
{
ReplyWithError(1);
return;
}
if (!Directory.Exists(Path.GetDirectoryName(fsFile)))
{
Directory.CreateDirectory(Path.GetDirectoryName(fsFile));
}
// are we allowed to write this type of file?
if (!_fileHooks.ContainsKey(fileName))
{
ReplyWithError(1);
return;
}
string backupFile = null;
int result = _fileHooks[fileName](fileData, fsFile, out backupFile);
if (result > 0)
{
ReplyWithError(result);
return;
}
Log.Info(string.Format("Got a request for writing {0} bytes to file {1} for user {2}.", fileData.Length, fileName, npid.ToString("X16")));
try
{
var stream = File.Open(fsFile, FileMode.Create, FileAccess.Write);
stream.BeginWrite(fileData, 0, fileData.Length, WriteCompleted, stream);
if (backupFile != null)
{
var backupStream = File.Open(backupFile, FileMode.Create, FileAccess.Write);
backupStream.BeginWrite(fileData, 0, fileData.Length, BackupWriteCompleted, backupStream);
}
}
catch (Exception ex)
{
Log.Error(ex.ToString());
ReplyWithError(2);
}
}
Yes, the very program that gives you this message may be the program that is locking the file. Make sure to practice good housekeeping by closing each data stream after it has been used.
var stream = File.Open(fsFile, FileMode.Create, FileAccess.Write);
Where do you close this stream again?
The process cannot access the file xxx because it is being used by another process.
The Microsoft programmer that wrote this message was a trust-hearty soul. He did not want to assume that you got it wrong. When you are debugging your code, that message should however have ended with "is being used by a process". It includes your own.
Also note that you made the same mistake with backupStream. Since you are already using File.ReadAllBytes() to read the file, you might just as well use File.WriteAllBytes() to write it. If you can't afford the delay then you'll need to ensure it is closed in the WriteCompeted callback method.
If you already do this, then consider that the file might actually be in use by another process. Which does happen.
I'm trying to use DotNetZip to handle zip files, but whenever I try to open a file I get the following error:
[SEVERE] System.ArgumentException: FileStream will not open Win32 devices such as disk partitions and tape drives. Avoid use of "\\.\" in the path.
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at Ionic.Zip.ZipEntry.InternalExtract(String baseDir, Stream outstream, String password)
at Ionic.Zip.ZipEntry.Extract(String baseDirectory)
at Ionic.Zip.ZipFile._InternalExtractAll(String path, Boolean overrideExtractExistingProperty)
at Ionic.Zip.ZipFile.ExtractAll(String path)
at ModsInstaller.Form1.MergeDirectories(String Path1, String Path2) in C:\Users\Admin\documents\visual studio 2010\Projects\ModsInstaller\ModsInstaller\Form1.cs:line 275
at ModsInstaller.Form1.CustomInstallForge() in C:\Users\Admin\documents\visual studio 2010\Projects\ModsInstaller\ModsInstaller\Form1.cs:line 259
at ModsInstaller.Form1.btn_install_Click(Object sender, EventArgs e) in C:\Users\Admin\documents\visual studio 2010\Projects\ModsInstaller\ModsInstaller\Form1.cs:line 120
and here's the code:
private void MergeDirectories(string Path1, string Path2)
{
string outDirectory = Path.GetFullPath(workspace + "\\temp\\dir");
if (!Directory.Exists(outDirectory))
Directory.CreateDirectory(outDirectory);
Path1 = Path.GetFullPath(Path1);
Path2 = Path.GetFullPath(Path2);
Log("Extracting {0} to temp dir.", Path1);
using (ZipFile zip = ZipFile.Read(Path1))
{
zip.ExtractAll(outDirectory); //this line throws the error
}
Log("Extraction sucessfull");
Log("Extracted {0} to temp dir.", Path2);
ZipFile.Read(Path2).ExtractAll(Path.GetFullPath(workspace + "\\temp\\dir"));
Log("Extraction sucessfull");
ZipFile z = new ZipFile(workspace + "\\temp\\build.jar");
z.AddDirectory(workspace + "\\temp\\dir");
z.Save();
z.Dispose();
}
and when I insert a breakpoint I see that:
outDirectory = "C:\\Users\\Admin\\documents\\visual studio 2010\\Projects\\ModsInstaller\\ModsInstaller\\bin\\Debug\\temp\\dir"
Can anyone point out what I'm doing wrong?
Thanks.
I had the same error with CON file name. It is not because of Ionic.Zip lib., but rather due to the Windows file naming convention.
Check the content of the first ZIP file if it has some unusual file names.
For example, in Windows you cannot create file with name CON, AUX, NUL, COM1, etc.
You can read more about it in reserved names section:
https://learn.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#file_and_directory_names
Solution to it is to take other zip file for testing or extract it under unix system or ask file provider to send vulnerable file(s) with differentia file name or at least lower case.
Usage
MergeDirectories("Sample 1.zip", "Sample 2.zip", "Merged.zip");
Code:
private void MergeDirectories(string filePath1, string filePath2, string mergedName)
{
string workspace = Environment.CurrentDirectory;
filePath1 = Path.Combine(workspace, filePath1);
filePath2 = Path.Combine(workspace, filePath2);
mergedName = Path.Combine(workspace, mergedName);
if (File.Exists(mergedName))
{
File.Delete(mergedName);
}
DirectoryInfo zip1 = OpenAndExtract(filePath1);
DirectoryInfo zip2 = OpenAndExtract(filePath2);
string merged = Path.GetTempFileName();
using (ZipFile z = new ZipFile())
{
z.AddDirectory(zip1.FullName);
z.AddDirectory(zip2.FullName);
z.Save(merged);
}
zip1.Delete(true);
zip2.Delete(true);
File.Move(merged, mergedName);
}
private DirectoryInfo OpenAndExtract(string path)
{
string tmpName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
string tmp = Path.Combine(Path.GetTempPath(), tmpName);
FileInfo sourcePath = new FileInfo(path);
DirectoryInfo tempPath = Directory.CreateDirectory(tmp);
using (ZipFile zip = ZipFile.Read(sourcePath.FullName))
{
zip.ExtractAll(tempPath.FullName);
}
return tempPath;
}
The following line is throwing an exception. I have no idea why.
using (var output = new FileStream(sftpFile.Name, FileMode.Create,FileAccess.ReadWrite))
Exception is:
Error: System.UnauthorizedAccessException: Access to the path 'C:\Users\roberth\
Programming_Projects\Common\UI\bin\Debug' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access,
Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions
options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy,
Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
at CWD.Networking.DownloadFromSftp(String hostname, String user, String passw
ord, Int32 port, String localPath, String remotePath, String filename) in c:\Use
rs\roberth\Programming_Projects\Common\Common\Common.cs:line 566
Line 566 is the using statement above.
Can anyone shed some light as to why I may be triggering an error? I have full permissions to the directory, no compilation issues, I can create new files and folders manually in that directory as well.
--Edit--
I tried running VS as administrator as suggested with no resolution.
The UnauthorizedAccessException error message tells you what file it is you're trying to open:
C:\Users\roberth\Programming_Projects\Common\UI\bin\Debug
This looks like a directory name: you can't open a directory as a file.
You've presumably forgotten to append a filename:
string filename = Path.Combine(sftpFile.Name, "SomeFile.dat");
using (var output = new FileStream(filename,...)
{
...
}
You need to use something similar to the following:
private bool EnviarArchivoSFTP(string PuertoSFTP, string UrlFTP, string CarpetaFTP, string UsuarioFTP, string PasswordFTP, string FicheroFTP, string nombreArchivo)
{
bool archivoEnviado = false;
using (var client = new SftpClient(UrlFTP, int.Parse(PuertoSFTP), UsuarioFTP, PasswordFTP))
{
client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(1);
client.OperationTimeout = TimeSpan.FromSeconds(1);
client.Connect();
client.ChangeDirectory(CarpetaFTP);
string dataPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string appFile = Path.Combine(dataPath, FicheroFTP, nombreArchivo);//Se brindan permisos full sobre la carpeta
using (var fileStream = new FileStream(appFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
client.BufferSize = 4 * 1024; // bypass Payload error large files
client.UploadFile(fileStream, Path.GetFileName(nombreArchivo));
archivoEnviado = true;
}
}
return archivoEnviado;
}