How to fix System.UnauthorizedAccessException when decompressing bz2 file? - c#

Im trying to decompress a bz2 file via code using the ICSharpCode.SharpZipLib.
It seems no matter where I make my file, even though I have FULL ACCESS control over it, I keep getting this Exception. Any help greatly appreciated.
using System;
using System.IO;
using ICSharpCode.SharpZipLib.BZip2;
namespace decompressor
{
class MainClass
{
public static void Main(string[] args)
{
string filePath = "C:\\FreeBase\\opinions.tsv.bz2";
string decompressPath = "C:\\Users\\mike\\Desktop\\Decompressed";
Console.WriteLine("Decompressing {0} to {1}", file, path);
BZip2.Decompress(File.OpenRead(filePath),File.OpenWrite(decompressPath), true);
}
}
}

Your code can have no access to create new paths at your desktop.
Check the permissions for the "C:\\Users\\mike\\Desktop\\Decompressed".

Maybe, you should write so:
string decompressPath = "C:\\Users\\mike\\Desktop\\Decompressed\\opinions.tsv";

Related

downloading the content of an xml file from Azure Blob Storage

In order to prevent the usual issues where I have an Xml file in a folder in one project and want to access it from other projects and have to deal with the file path issues, I want to download the Xml file contents directly from Azure blob storage where it resides now.
Not sure how to accomplish that although I see many examples of how to download images into streams, not sure how that works for Xml.
I am currently using the following ( which works until I move the Xml file)
public class MenuLoader
{
//var rootpath = HttpContext.Current.Server.MapPath("~");
private static readonly string NavMenuXmlPath = Path.Combine(ServicesHelpers.GetClassLibraryRootPath(),
#"ServicesDataFiles\MRNavigationMenu.xml");
);
//load the menus, based on the users role into the AppCache
public static void LoadMenus(IPrincipal principal)
{
var navXml = new NavigationMenusFromXml(NavMenuXmlPath);
var nmim = new NavigationMenuItemManager(navXml);
AppCache.Menus = nmim.Load(principal);
}
}
I want to eliminate all the bs associated with path combining and just download the xml from the file on Azure, i.e. replacing the string
#"ServicesDataFiles\MRNavigationMenu.xml"
with
"https://batlgroupimages.blob.core.windows.net:443/files/MRNavigationMenu.xml"
Naturally, that wouldn't work but there must be someway to load that xml into a file variable for use with the method.
Note: That is a publicly accessible file on azure for testing.
Use a memory stream. Remember to set position to zero before attempting to read.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
const string URL = "https://batlgroupimages.blob.core.windows.net/files/MRNavigationMenu.xml";
static void Main(string[] args)
{
MemoryStream stream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(stream);
XmlDocument doc = new XmlDocument();
doc.Load(URL);
writer.WriteRaw(doc.OuterXml.ToString());
writer.Flush();
}
}
}

how to write a file to Local Document library

i am using streamwriter to write the file, however the location of the new written file is located within one of the folder with in the project folder but i would like the location to be on the document library of the computer. im using a mvc application not a console Application
Any help would be appreciate.
thank you
using (var File = new StreamWriter(System.Web.HttpContext.Current.Server.MapPath("~/OutputFileTest.csv"), false)) // true for appending the file and false to overwrite the file
{
foreach (var item in outputFile)
{
File.WriteLine(item);
}
}
From MSDN:
// Sample for the Environment.GetFolderPath method
using System;
class Sample
{
public static void Main()
{
Console.WriteLine();
Console.WriteLine("GetFolderPath: {0}",
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
}
}
/*
This example produces the following results:
*/

why c# console command not running on java?

Can anyone tell me why this c# console command not running on Java?
I've made a C# console program as given below:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace face
{
class Program
{
public static void Main(string[] args)
{
String path = args[0];
byte[] imageBytes = File.ReadAllBytes(path);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
Bitmap S1 = new Bitmap(image);
Console.WriteLine(S1.GetPixel(2, 10));
}
}
}
When I run Program.exe image.jpg, I get:
Color [A=255, R=128, G=32, B=128]
Then I created a simple Java application to run the Program.exe executable:
class project
{
public static void main(String[] args)
{
String comman="C:\\WINXP\\system32\\Program.exe Sunset.jpg";
try
{
Process process = Runtime.getRuntime().exec(comman);
System.out.println(process.getOutputStream());
} catch (Exception e)
{e.printStackTrace(System.err);}
}
}
When I try to run the Java application, I get the following error:
Program.exe has encountered a problem and needs to close. We are sorry for the inconvenience.
You probably want to change
String comman = "C:\\WINXP\\system32\\Program.exe Sunset.jpg";
to
String[] comman = { "C:\\WINXP\\system32\\Program.exe", "Sunset.jpg" };
As a comment said, it's probably because the C# program can't open the file: you should specify an absolute path for it, since getting the actual working directory to work right can be an unnecessary pain in this situation. Also it wouldn't hurt to catch exceptions in the C# program (for example for the "no arguments" and "file not found" cases).
The C# process is a child process of the java process, and killed automatically then the java VM terminates. Because the process is started asynchronously, that will happen immediately. If you're interested in the output, replace
System.out.println(process.getOutputStream());
with (for instance)
InputStream inputStream = process.getInputStream();
int c;
while ((c = inputStream.read()) >= 0) {
System.out.print((char) c);
}
if not, write
process.getInputStream().close();
process.waitFor();
Apart from what others have said, I don't think that System.out.println(process.getOutputStream()); will output what you want here - namely the output of the executed C# executable.
System.out.println() has no overload for OutputStream, the return type of Process.getOutputStream(). So the System.out.println(Object) overload will be choosen, which will call OutputStream.ToString(), which is not the output of the C# program, but (most likely, bear with me here) the fully qualified typename of the output stream instance.
Check this SO question/answer, for example, for more information.
You need to check path of exe and image file that you have provided. As I check this code and execute it then I get following output
java.io.BufferedOutputStream#c17164
Here I provide you your modified code
public class Test
{
public static void main(String[] args)
{
String path="C:\\C#Sample\\ImageDisplayDemo\\ImageDisplayDemo\\bin\\Debug\\ImageDisplayDemo.exe E:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg";
try
{
Process proc=Runtime.getRuntime().exec(path);
System.out.println(proc.getOutputStream());
}
catch(Exception ex)
{
}
}
}

Create file without opening/locking it?

Does anyone know of a way to (reasonably simple) create a file without actually opening/locking it? In File class, the methods for file creation always return a FileStream. What I want to do is to create a file, rename it (with File.Move) and then use it.
Now I have to:
Create it
Close
Rename
Reopen for use
Maybe you can try using File.WriteAllText Method (String, String)
with the file name and an empty string.
Creates a new file, writes the
specified string to the file, and then
closes the file. If the target file
already exists, it is overwritten.
using (File.Create(...)) { }
While this will briefly open your file (but close it again right away), the code should look quite unobtrusive.
Even if you did some P/Invoke call to a Win32 API function, you would get a file handle. I don't think there's a way to silently create a file without having it open right afterwards.
I think the real issue here is why you go about creating your file in the way you've planned. Creating a file in one place simply to move it to another location doesn't seem very efficient. Is there a particular reason for it?
What about using File.WriteAllBytes method?
// Summary:
// Creates a new file, writes the specified byte array to the file, and then
// closes the file. If the target file already exists, it is overwritten.
Another way is to use FileStream and Close it after creating the file. It will not lock the file. The code will look like:
FileStream fs = new FileStream(filePath, FileMode.Create);
fs.Flush(true);
fs.Close();
You just after this you can rename it as well or move it some other location.
Below is the Test program to test functionality.
using System;
using System.Collections.Generic;
using System.IO; using
System.Linq;
using System.Text;
namespace FileLocking {
class Program
{
static void Main(string[] args)
{
string str = #"C:\Test\TestFileLocking.Processing";
FileIOTest obj = new FileIOTest();
obj.CreateFile(str);
}
}
class FileIOTest
{
internal void CreateFile(string filePath)
{
try
{
//File.Create(filePath);
FileStream fs = new FileStream(filePath, FileMode.Create);
fs.Flush(true);
fs.Close();
TryToAccessFile(filePath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
void TryToAccessFile(string filePath)
{
try
{
string newFile = Path.ChangeExtension(filePath, ".locked");
File.Move(filePath, newFile);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
} }
If you use File.Create(commented in above code) then it will give error saying file is being used by another process.
Incredibly grotty hack, probably the most complicated way to achieve your goal:
use Process class
processInfo = new ProcessStartInfo("cmd.exe", "/C " + Command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
process = process.Start(processInfo);
process.WaitForExit();
where Command would be echo 2>> yourfile.txt

How to append text to multiple files

I am not a programmer, but I am a researcher and I need to modify some files.
I have a number of text files with *.mol extension located in c:\abc\ directory . I need to append line containing following text "M END" to each file in this list. I tried following in C# but without any result:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
StreamWriter sw = new StreamWriter("c:\\abc\\*.mol", true);
sw.WriteLine("M END");
sw.Close();
}
}
}
Please, suggest the solution.
Thank You!
Would you be satisfied with this oneliner that you can put in any DOS batch (.bat) file:
FOR %%I IN (c:\abc\*.mol) DO ECHO M END>>%%I
foreach (string fileName in Directory.GetFiles("directory", "*.mol"))
{
File.AppendAllText(fileName, Environment.NewLine + "M END");
}
You'll need to loop through all the files matching that pattern and write to them individually. The StreamWriter constructor you're using only supports writing to an individual file (source).
You can get a list of files using:
string[] filePaths = Directory.GetFiles("c:\\abc\\", "*.mol");
You need to iterate over the files in the directory. DirectoryInfo / FileInfo makes it easy to do this. Also, since you want to append to the end, you need to seek the stream before writing your signature at the end.
Here's a solution that works solely at that location. You will need to add recursive support to descend into subdirectories if desired.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace appender
{
class Program
{
static void AppendToFile(FileInfo fi)
{
if (!fi.Exists) { return; }
using (Stream stm = fi.OpenWrite())
{
stm.Seek(0, SeekOrigin.End);
using (StreamWriter output = new StreamWriter(stm))
{
output.WriteLine("M END");
output.Close();
}
}
}
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo("C:\\abc\\");
FileInfo[] fiItems = di.GetFiles("*.mol");
foreach (FileInfo fi in fiItems)
{
AppendToFile(fi);
}
}
}
}

Categories