Hello i want to access my files at resources in Visual Studio but when i Build my .exe file and move it from my Folder i get a message that the files could not be found?
That is my code:
string RunningPath = AppDomain.CurrentDomain.BaseDirectory;
string pdf = string.Format("{0}Resources\\me.pdf", Path.GetFullPath(Path.Combine(RunningPath, #"..\..\")));
Process.Start(pdf);
I tried other methods but it still don't work? :/
Anyone has an idea?
something you could do like this read a file from resource stream
var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("me.pdf");
using (FileStream fs = File.Create(#"c:\temp\me.pdf"))
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, len);
}
};
Process.Start(#"c:\temp\me.pdf");
If you have added the pdf file to Properties.Resources, you can access it as followed.
Call AppDomain.CurrentDomain.BaseDirectory to get bin\Debug folder first.
Then use .. to return to the parent directory
string path = AppDomain.CurrentDomain.BaseDirectory + #"..\..\Resources\test.pdf";
System.Diagnostics.Process.Start(path);
Related
This question already has an answer here:
File.Delete the process cannot access the file because it is being used by another process
(1 answer)
Closed 2 years ago.
I need to create small console application to move files into separate folders. Everything works fine, I can copy file, until I try to File.Move or File.Delete file, I catch System.UnauthorizedAccessException. What I've tried
changing folder permission from code
switching from .Net Core to .Net Framework
Manually adding permission to folder by rightclicking->Security->Advance
tried to change Folder's Read-only attribute (it always reverts back to readonly, I can't solve this)
I don't know what else I can try and how to solve this problem. The code I wrote is below
var pngFiles = Directory.GetFiles(#"C:\Users\MSI_PC\Desktop\Test", "*.png",
SearchOption.AllDirectories);
foreach (var pngFile in pngFiles)
{
Console.WriteLine(pngFile);
var fileName = Path.GetFileName(pngFile);
var newFolder = Path.Combine(#"C:\Users\MSI_PC\Desktop\Test",
Path.GetFileNameWithoutExtension(fileName));
Directory.CreateDirectory(newFolder);
var newFileName = Path.Combine(#"C:\Users\MSI_PC\Desktop\Test",
Path.GetFileNameWithoutExtension(fileName), fileName);
File.Copy(pngFile, newFileName, true); //yes, I can use move and have 1 line of code instead of 2. But I need file to be copied, and this line of code works fine
File.Delete(pngFile); // System.UnauthorizedAccessException. File.Move throws the same exception
}
try this code
private void Copy()
{
var pngFiles = Directory.GetFiles(#"C:\Users\Administrator\Desktop", "*.png", SearchOption.AllDirectories);
foreach (var pngFile in pngFiles)
{
Console.WriteLine(pngFile);
var fileName = Path.GetFileName(pngFile);
var newFolder = Path.Combine(#"D:\NewPic\");
Directory.CreateDirectory(newFolder);
string DestPath = newFolder + "\\" + fileName;
byte[] buffer = new byte[2014 * 1024];
using (FileStream source = new FileStream(pngFile, FileMode.Open, FileAccess.Read, FileShare.Delete))
{
using (FileStream dest = new FileStream(DestPath, FileMode.CreateNew, FileAccess.Write, FileShare.Delete))
{
int currentBlockSize = 0;
while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, currentBlockSize);
}
dest.Close();
}
source.Close();
}
File.Delete(pngFile); // System.UnauthorizedAccessException. File.Move throws the same exception
}
}
I'm using a C# wrapper to convert PDFs to images using Ghostscript, however i cant seem to reference the dll correctly.
I have the DLL stored in the bin folder (also don't know if that's the best place to keep it there or not)
Here's my code:
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
Ghostscript.NET.Rasterizer.GhostscriptRasterizer rasterizer = null;
Ghostscript.NET.GhostscriptVersionInfo vesion = new Ghostscript.NET.GhostscriptVersionInfo(new Version(0, 0, 0), path + #"\gsdll64.dll", string.Empty, Ghostscript.NET.GhostscriptLicense.GPL);
Stream inStream = new MemoryStream(fileData);
MemoryStream outStream = new MemoryStream();
List<Image> imageList = new List<Image>();
using (rasterizer = new Ghostscript.NET.Rasterizer.GhostscriptRasterizer())
{
rasterizer.Open(inStream, vesion, false);
for (int i = 1; i <= rasterizer.PageCount; i++)
{
//string pageFilePath = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(file) + "-p" + i.ToString() + ".jpg");
int dpi = 200;
Image img = rasterizer.GetPage(dpi, dpi, i);
img.Save(outStream, ImageFormat.Jpeg);
Image img = new Image
{
imgByteArray = outStream.ToArray()
};
imageList.Add(image);
}
rasterizer.Close();
}
I'm getting the Ghostscript native library could not be found error.
Here's the path I get
I think it has to do with the double / and 'file://' in the DLLPath string. And should I also specify the LipPath as well?
Any help??
In your case you should make ghostscript dll path this way:
string binPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string gsDllPath = Path.Combine(binPath, Environment.Is64BitProcess ? "gsdll64.dll" : "gsdll32.dll");
Even though this does not answer the question directly, I think it's worth mentioning, because I've ran into a problem using the OP's code with Ghostscript.NET version 1.2.1 published in 2016. Here's the fix I found:
In the source code,
Ghostscript.NET\Helpers\StreamHelper.cs:171
n = output.Read(buffer, 0, buffer.Length);
really should've been
n = input.Read(buffer, 0, buffer.Length);
If you're opening a stream instead of a path, without modifying the above mentioned code, you'll get empty result because the input stream did not get copied.
Reading into the code in more depth finds that the input stream is written into a temp file then read again into memory. You'll be better off just using rasterizer.Open by the path instead of stream, if it were a PDF file on disk to begin with.
I created a report using ReportViewer and I can generate it on local machine without any problem. On the other hand, I encounter an error "Access to the path 'C:\xxxxxxx.xlsx' is denied." after publishing the application to IIS. Of course it is caused by the permission problem, but in our company, in most cases there is no writing permission to any location of C drive and I think the best approach is to open the generated excel file in memory, etc. (without writing to disk). So, how can I update the method I use in order to achieve this? Any idea?
I send the report (created using ReportViewer) to this method as Stream and I open the generated report without writing to disk:
public static void StreamToProcess(Stream readStream, string fileName, string fileExtension)
{
var myFile = fileName + "_" + Path.GetRandomFileName();
var writeStream = new FileStream(String.Format("{0}\\{1}.{2}",
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), myFile,
fileExtension), FileMode.Create, FileAccess.Write);
const int length = 16384;
var buffer = new Byte[length];
var bytesRead = readStream.Read(buffer, 0, length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, length);
}
readStream.Close();
writeStream.Close();
Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.
InternetCache) + "\\" + myFile + "." + fileExtension);
}
Any help would be appreciated.
Update :
I pass the report stream to this method as shown below:
StreamToProcess(reportStream, "Weekly_Report", "xlsx");
Note : reportStream is the generated report using ReportViewer.
You can write to a MemoryStream instead and return this stream to the caller. Make sure you do not close the instance of your memory stream. You can then pass this memory stream to a StreamWriter instance if you want to process the in-memory file.
public static Stream StreamToProcess(Stream readStream)
{
var myFile = fileName + "_" + Path.GetRandomFileName();
var writeStream = new MemoryStream();
const int length = 16384;
var buffer = new Byte[length];
var bytesRead = readStream.Read(buffer, 0, length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, length);
}
readStream.Close();
return writeStream;
}
Your current approach of calling Process.Start will not work on the IIS server as it will open the Excel document on the server rather than on the users computer. You will have to provide a link to the user to download the file, you could use an AJAX request for this that streams from the MemoryStream. Have a look at this post on further details on how to implement this.
I am using the code below to upload a file. The files upload without error, but when I open a file with a .docx extension M$ says that the file is corrupted. It is able to repair the file and then open, however. I'd like to fix this so the document opens correctly.
string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
string fileName = #"C:\" + Guid.NewGuid().ToString() + strExtension;
using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
byte[] bytes = new byte[16 * 1024];
int bytesRead;
while ((bytesRead = context.Request.InputStream.Read(bytes, 0, bytes.Length)) > 0)
{
fs.Write(bytes, 0, bytesRead);
}
}
Thanks.
EDITED:
File saves correctly with this code:
while ((bytesRead = context.Request.Files[0].InputStream.Read(bytes, 0, bytes.Length)) > 0)
Also saves correctly with context.Request.Files[0].SaveAs(...);
It looks like you are reading the HttpRequest.InputStream. The better thing to do is check the HttpRequest.Files collection.
(Or even easier, use a FileUpload server control).
Your code is copying the raw input, which is most likely multi-part, to a file.
This doesn't answer your question exactly, but you could use HttpPostedFile.SaveAs to save the content to the desired path.
string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
string fileName = #"C:\" + Guid.NewGuid().ToString() + strExtension;
context.Request.Files[0].SaveAs(fileName); // i'll ignore the violation of the law of demeter ;)
I have some files, which are embedded in a resource. How can I save these files on disk via C#?
This should do your job:
string strTempFile = Path.GetTempFileName();
File.WriteAllBytes(strTempFile, Properties.Resources.YourBinaryFileInResource);
Be sure, that the FileType of the included files is set to "binary".
using streams: GetManifestResourceStream gives you a stream to the file in the resource and using a StreamWriter you can write the contents of that stream to disk.
You can get the resource stream, then read from the stream while writing to the file.
byte[] buffer = new byte[1024];
using (Stream output = File.OpenWrite("filename"))
{
using (Stream resourceStream = typeof(Class1).Assembly.GetManifestResourceStream("name of resource"))
{
int bytes = -1;
while ((bytes = resourceStream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytes);
}
}
}
Code is completely untested, just to give you an idea.