System.IO.IOException: Read-only file system at Interop.ThrowExceptionForIoErrno - c#

When I deploy my changes to azure web app I am getting below exception :
enter image description here
But no local it's working fine.
I have check my file IsReadOnly=false or not.
Using a below code to achieve
var fileName = "myfilename.json";
var filePath = Path.Combine(Directory.GetCurrentDirectory(), fileName);
var configJSON = JsonConvert.SerializeObject(integrationsConfiguration);
cancellationToken.ThrowIfCancellationRequested();
FileInfo fileInfo = new FileInfo(fileName);
fileInfo.IsReadOnly = false;
using (FileStream fs = new FileStream(filePath, FileMode.Truncate, FileAccess.ReadWrite))
using (TextWriter writer = new StreamWriter(fs))
{
writer.WriteLine(configJSON);
}
return true;

Related

C# - Trying to grab and save a pdf into my database

In my C# application, I am trying to make it able to pull a pdf and save it, so that end users can press a button and pull up that pdf while they are in the application. But when I copy the content to the filestream it makes the pdf but it is just blank with nothing from the original pdf. What am I doing wrong?
The pdf's could also have pictures on them, and I don't think the way I'm doing it would allow those to be brought over.
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
bool? response = openFileDialog.ShowDialog();
var fileContent = string.Empty;
var filestream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(filestream))
{
fileContent = reader.ReadToEnd();
}
// make folder path
string FolderPath = "ProjectPDFs\\";
string RootPath = "X:\\Vents-US Inventory";
DirectoryInfo FolderDir = new DirectoryInfo(Path.Combine(RootPath, FolderPath));
Directory.CreateDirectory(FolderDir.ToString());
string filePath = "";
string FileName = openFileDialog.SafeFileName;
if (fileContent.Length > 0)
{
filePath = Path.Combine(FolderDir.ToString(), FileName);
using (Stream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
byte[] bytestream = Encoding.UTF8.GetBytes(fileContent);
Stream stream = new MemoryStream(bytestream);
stream.CopyTo(fileStream);
}
}

How to stream a file in aws lambda using c#

I am uploading an evidence file to stripe using filestream but apllication was hosted in aws lambda which is not supporting filestream.
Here is my code
public async Task<IActionResult> PostFile(D.StripeFilePurpose stripeFilePurpose)
{
IFormFile file = Request.Form.Files[0];
var fileName = ContentDispositionHeaderValue.Parse(
file.ContentDisposition).FileName.Trim('"');
var path = string.Empty;
var webRootPath = _hostingEnvironment.WebRootPath;
if (string.IsNullOrEmpty(webRootPath))
{
path = Directory.GetCurrentDirectory();
}
string fileId;
var filePath = Path.Combine(path, fileName);
using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
file.CopyTo(fileStream);
}
using (var stream = new FileStream(filePath, FileMode.Open))
{
var stripeFileUpload = await _stripeDisputeService
.UploadFileAsync(
fileName,
stream,
stripeFilePurpose.GetDescription());
fileId = stripeFileUpload.Id;
}
return StatusCode(200, fileId);
}
whenever specifying a filepath lamba was appending it with /var/task/**mypath.
I even hardcoded filepath still appending /var/task before file path. I searched and found that streaming is possible only if we store file in /tmp folder(lambda)..
How to achieve this??
You can try using a MemoryStream instead.
public async Task<IActionResult> PostFile(D.StripeFilePurpose stripeFilePurpose)
{
IFormFile file = Request.Form.Files[0];
var fileName = file.FileName.Trim('"');
using MemoryStream memStream = new MemoryStream();
await file.CopyToAsync(memStream);
memStream.Position = 0;
var stripeFileUpload = await _stripeDisputeService
.UploadFileAsync(
fileName,
memStream,
stripeFilePurpose.GetDescription());
fileId = stripeFileUpload.Id;
return StatusCode(200, fileId);
}
It will consume more memory in the service, but avoid disk usage.

Cannot create file "c:\User\...\Appdata\Roaming...". Access is denied

I want to store certain .txt file during app lifetime. I was thinking to use Environment.SpecialFolder.ApplicationData
so I created
string myFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), address.GetHashCode() + ".txt");
...
File.WriteAllText(myFilename, someTextContent);
I'm getting
Cannot create file "c:\User...\Appdata\Roaming...". Access is denied.
Consider using Isolated Storage, you have guaranteed read/write access with it.
Writing:
IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("TestStore.txt", FileMode.CreateNew, isoStore))
{
using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.WriteLine("Hello Isolated Storage");
}
}
Reading:
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("TestStore.txt", FileMode.Open, isoStore))
{
using (StreamReader reader = new StreamReader(isoStream))
{
string contents = reader.ReadToEnd();
}
}

IsolatedStorageFile.FileExists(string path) works but StreamReader(string samePath) doesn't?

IsolatedStorageFile.FileExists(string path) works but StreamReader(string samePath) doesn't?
I have validated both paths are equal. I have no idea why the StreamReader explodes
List<ProjectObj> ret = new List<ProjectObj>();
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
if (!file.DirectoryExists("/projects/")) //trying to validate the dir exists
return ret;
string[] fileNames = file.GetFileNames("/projects/");
foreach (string filename in fileNames)
{
if (!file.FileExists("/projects/" + filename)) //validate just one more time..
continue;
ProjectObj tempProj = new ProjectObj();
//Even with the validation it still breaks right here with the bellow error
StreamReader reader = new StreamReader("/projects/"+filename);
An exception of type 'System.IO.DirectoryNotFoundException' occurred
in mscorlib.ni.dll but was not handled in user code
Message:Could not find a part of the path
'C:\projects\Title_939931883.txt'.
Path is not same in both cases. In first case you are getting User store for application and then search for file in it. But in later case you are simply searching in base directory.
StreamReader constructor expects absolute path of file.
You need to create IsolatedStorageFileStream and pass it on to StreamReader -
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream
("/projects/" + filename, FileMode.Open, file))
{
using (StreamReader reader = new StreamReader(fileStream ))
{
}
}
Give this one a try. Reading and writing files in IsolatedStorage has a different path and should be used like that. You should consider reading How to: Read and Write to Files in Isolated Storage.
public static List<ProjectObj> getProjectsList()
{
List<ProjectObj> ret = new List<ProjectObj>();
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
if (!file.DirectoryExists("/projects/")) //trying to validate the dir exists
return ret;
string[] fileNames = file.GetFileNames("/projects/");
foreach (string filename in fileNames)
{
if (!file.FileExists("/projects/" + filename)) //validate just one more time...
continue;
ProjectObj tempProj = new ProjectObj();
using (var isoStream = new IsolatedStorageFileStream("/projects/" + filename, FileMode.Open, FileAccess.Read, FileShare.Read, file))
{
using (StreamReader reader = new StreamReader(isoStream))
{
}
}
This was the solution I came up with
List<ProjectObj> ret = new List<ProjectObj>();
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
if (!file.DirectoryExists("/projects/"))
return ret;
foreach (String filename in file.GetFileNames("/projects/"))
{
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("/projects/"+filename, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{
String fileInfo = reader.ReadToEnd();
}
}
I don't know why I was getting the illegal operation on boot of app but I know why it was happening later on. I guess when you try and access the same file to quickly it causes errors. So I added in a fileshare and also I made sure to dispose of other accesses before this ran.

c# Replace openfileDialog to a none gui stream

I am trying to separate the MIME gui from the code i need. I am almost there just one more gui element i dont know how to replace. This element is the openfiledialog. Here a code snippet.
Program.cs
var sfd = new OpenFileDialog();
sfd.FileName = "C:\\eml\\" + validOutputFilename;
try
{
var writer = new MimeMessageWriter();
using (var fs = sfd.OpenFile()) writer.Write(message, fs);
}
catch (Exception ex)
{
//ignore
// need to log
}
message is an IMessage. A class created to store the information about an eml file. The open file dialog is allowing you to put in the file name with an eml extension and that is all. write.Write expects an IMessage and a stream. Inside writer.Write the file is being written The only part of the file that uses this code is when the file itself is writen at the end and write out any attachments. Here are those code snippets.
*MimeMessageWriter
-the attachment uses it here
var embeddedMessage = attachment.OpenAsMessage();
var messageWriter = new MimeMessageWriter();
var msgStream = new MemoryStream();
messageWriter.Write(embeddedMessage, msgStream);
var messageAttachment = ew DotNetOpenMail.FileAttachment(msgStream.ToArray());
messageAttachment.ContentType = "message/rfc822";
messageAttachment.FileName = filename + ".eml";
outMessage.AddMixedAttachment(messageAttachment);
-write out the file part of the file
using (var sw = new StreamWriter(stream))
sw.Write(outMessage.ToDataString());
I want to replace openFileDialog with something that will allow me to pass the filename to write out file in the MimeMessageWriter
Replace
using (var fs = sfd.OpenFile()) writer.Write(message, fs);
with
string fileName = #"c:\eml\myAttachment.eml";
using ( FileStream fs = new FileStream( fileName, FileMode.CreateNew ) )
{
writer.Write( message, fs )
}
See also: http://msdn.microsoft.com/de-de/library/47ek66wy.aspx

Categories

Resources