File is getting locked on read/write operation in C# - windows

A third party application is reading the output text file of my windows application,it is getting paused.I think,it is happening because of file gets locked either on writing or reading.how can i make this work fine.Please see my code.
List<string> fileList = new List<string>();
System.Timers.Timer timer;
string currentfilename;
string currentcontent;
public Service1()
{
//
timer = new System.Timers.Timer();
timer.AutoReset = false;
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
throw new NotImplementedException();
}
private void DoStuff(object sender, System.Timers.ElapsedEventArgs e)
{
DateTime LastChecked = DateTime.Now;
try
{
string[] files = System.IO.Directory.GetFiles(#"C:\Journal", "*.jrn", System.IO.SearchOption.AllDirectories);
foreach (string file in files)
{
if (!fileList.Contains(file))
{
currentfilename = file;
fileList.Add(file);
copywarehouse(file);
try
{
string sourcePath = #"C:\Journal";
string sourceFile = System.IO.Path.Combine(sourcePath, file);
using (FileStream fs= new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
StreamReader sr = new StreamReader(fs);
currentcontent = sr.ReadToEnd();
sr.Close();
}
}
catch (Exception ex)
{
throw (ex);
}
}
}
try
{
string sourcePath1 = #"C:\Journal";
string currentfilecontent;
string sourceFile1 = System.IO.Path.Combine(sourcePath1, currentfilename);
using (FileStream fs = new FileStream(sourceFile1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
StreamReader sr = new StreamReader(fs);
currentfilecontent = sr.ReadToEnd();
sr.Close();
}
if (currentfilecontent != currentcontent)
{
if (currentfilecontent.Contains(currentcontent))
{
string originalcontent = currentfilecontent.Substring(currentcontent.Length);
File.WriteAllText(#"C:\Journal\tempfile.txt", originalcontent + "\r\n");
using (FileStream fs = new FileStream(#"C:\Journal\tempfile.txt", FileMode.OpenOrCreate))
{
StreamWriter sw = new StreamWriter(fs);
sw.Write(originalcontent);
sw.Close();
}
currentcontent = currentfilecontent;
}
}
}
//}
catch (Exception ex)
{
throw (ex);
}
TimeSpan ts = DateTime.Now.Subtract(LastChecked);
TimeSpan MaxWaitTime = TimeSpan.FromMilliseconds(100);
if (MaxWaitTime.Subtract(ts).CompareTo(TimeSpan.Zero) > -1)
timer.Interval = MaxWaitTime.Subtract(ts).Milliseconds;
else
timer.Interval = 1;
timer.Start();
}
catch (Exception ex)
{
throw (ex);
}
}
private void copywarehouse(string filename)
{
string sourcePath = #"C:\Journal";
string targetPath = #"C:\Journal";
string copycontent=null;
try
{
string sourceFile = System.IO.Path.Combine(sourcePath, filename);
string destFile = System.IO.Path.Combine(targetPath, "tempfile.txt");
using (FileStream fs = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
StreamReader sr = new StreamReader(fs);
copycontent = sr.ReadToEnd();
sr.Close();
}
using (FileStream fs = new FileStream(destFile, FileMode.Append))
{
StreamWriter sw = new StreamWriter(fs);
sw.Write(copycontent);
sw.Close();
}
}
catch (Exception ex)
{
throw (ex);
}
}

Here the problem is with third party application which is reading my application output as input.it is not allowing access to more than one file content..

Related

Send multiple files from angular typescript to spring and return as zip folder for downloading?

I want to send multiple files in an array to spring and create a zip folder for downloading
UploadController:
#Autowired
StorageService storageService;
#PostMapping("/upload")
public ResponseEntity<ResponseMessage> uploadFiles(#RequestParam("files") MultipartFile[] files) {
String message = "";
try {
storageService.zip(files);
message = "Uploaded the files successfully";
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
} catch (Exception e) {
message = "Fail to upload files!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
}
}
StorageService
public void zip(MultipartFile[] files) {
List<Path> filepaths = new ArrayList();
for (MultipartFile file : files) {
Path filepath = Paths.get("my/tmp/dir", file.getOriginalFilename());
filepaths.add(filepath);
try (OutputStream os = Files.newOutputStream(filepath)) {
os.write(file.getBytes());
}
}
File zip = new File("path/to/my/zip");
try { zip.createNewFile(); }
FileOutputStream output = null;
try { output = new FileOutputStream(zip); }
ZipOutputStream out = new ZipOutputStream(output);
try {
for (Path filepath : filepaths) {
File f = new File(filepath);
FileInputStream input = new FileInputStream(f);
ZipEntry e = new ZipEntry(f.getName());
out.putNextEntry(e);
byte[] bytes = new byte[1024];
int length;
while((length = input.read(bytes)) >= 0) {
out.write(bytes, 0, length);
}
input.close();
}
out.close();
output.close();
}
}

"The request has already been submitted.” while working with Skydrive API in WP8

I am trying to use the SkyDrive API to upload a file. I tried using the below code.GEtAccountInformaiton and GetQuotaInformaiton methods are successfully executed But it always sets this error "The request has already been submitted.” at the end (in UploadISOFileToSkyDriveAsync() method for the field lblMessageBar.Text ).
private async void GetAccountInformations()
{
try
{
LiveOperationResult operationResult = await App.liveConnectClient.GetAsync("me");
var jsonResult = operationResult.Result as dynamic;
string firstName = jsonResult.first_name ?? string.Empty;
string lastName = jsonResult.last_name ?? string.Empty;
lblMessageBar.Text = "Welcome " + firstName + " " + lastName;
GetQuotaInformations();
}
catch (Exception e)
{
lblMessageBar.Text = e.ToString();
}
}
private async void GetQuotaInformations()
{
try
{
LiveOperationResult operationResult = await App.liveConnectClient.GetAsync("me/skydrive/quota");
var jsonResult = operationResult.Result as dynamic;
quota = jsonResult.quota ?? string.Empty;
available = jsonResult.available ?? string.Empty;
lblMessageBar.Text = "Available space in bytes: " + ConvertBytesToGigabytes(available).ToString("#.####") + "GB " + "out of bytes " + ConvertBytesToGigabytes(quota).ToString("#.####") + "GB";
UploadISOFileToSkyDriveAsync();
}
catch (Exception e)
{
lblMessageBar.Text = e.ToString();
}
}
public async void UploadISOFileToSkyDriveAsync()
{
try
{
//http://developer.nokia.com/Community/Wiki/SkyDrive_-_How_to_upload_content_on_Windows_Phone
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, FileMode.Append, fileStorage));
//get the data from local database and write to the isolated file and then use the path of this file to saved it to skydrive..
ObservableCollection<SavedLocationsTableEntity> SavedLocations = SavedLocationsTableEntity.GetSavedLocations();
foreach (SavedLocationsTableEntity item in SavedLocations)
{
Writer.WriteLine(UtilityLib.GetGoogleURL(new System.Device.Location.GeoCoordinate(item.SavedLocationLatitude, item.SavedLocationLongitude, item.SavedLocationAltitude)));
}
Writer.Close();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
fileStream = store.OpenFile("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, FileMode.OpenOrCreate, FileAccess.Read);
//strEncryptedFileStream = Encoding.Unicode.GetBytes(fileStream.ToString()).ToString();
if (fileStream.Length == 0)
{
lblMessageBar.Text = "No data to upload to SkyDrive..";
return;
}
fileStream.Close();
}
//remove previous calls
var reqList = BackgroundTransferService.Requests.ToList();
foreach (var req in reqList)
{
if (req.UploadLocation.Equals(new Uri(MyFilePathInIsoStore, UriKind.Relative)))
BackgroundTransferService.Remove(BackgroundTransferService.Find(req.RequestId));
}
//Make a new call to upload
LiveOperationResult res = await App.liveConnectClient.BackgroundUploadAsync("me/skydrive", new Uri("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, UriKind.Relative), OverwriteOption.Overwrite);
lblMessageBar.Text = "File " + Constants.SkyDriveSavedLocationsFileName + " uploaded.";
return;
}
catch (Exception ex)
{
lblMessageBar.Text = "Cannot upload to SkyDrive.. " + ex.Message;
return;
}
}
It looks like MyFilePathInIsoStore here:
if (req.UploadLocation.Equals(new Uri(MyFilePathInIsoStore
is not equals "/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName here:
new Uri("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, UriKind.Relative)

Convert csv to xls/xlsx using Apache poi?

I need to convert csv to xls/xlsx in my project? How can i do that? Can anyone post me some examples? I want to do it with Apache poi. I also need to create a cell from java side.
You can try following method to create xlsx file using apache-poi.
public static void csvToXLSX() {
try {
String csvFileAddress = "test.csv"; //csv file address
String xlsxFileAddress = "test.xlsx"; //xlsx file address
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int RowNum=0;
BufferedReader br = new BufferedReader(new FileReader(csvFileAddress));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split(",");
RowNum++;
XSSFRow currentRow=sheet.createRow(RowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileAddress);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage()+"Exception in try");
}
}
We can use SXSSF Jar in which we can parse a long file as below:
public static void main( String[] args ) {
try {
// String fName = args[ 0 ];
String csvFileAddress = "C:\\Users\\psingh\\Desktop\\test\\New folder\\GenericDealerReport - version6.txt"; //csv file address
String xlsxFileAddress = "C:\\Users\\psingh\\Desktop\\trial\\test3.xlsx"; //xlsx file address
SXSSFWorkbook workBook = new SXSSFWorkbook( 1000 );
org.apache.poi.ss.usermodel.Sheet sheet = workBook.createSheet( "sheet1" );
String currentLine = null;
int RowNum = -1;
BufferedReader br = new BufferedReader( new FileReader( csvFileAddress ) );
while ( ( currentLine = br.readLine() ) != null ) {
String str[] = currentLine.split( "\\|" );
RowNum++;
Row currentRow = sheet.createRow( RowNum );
for ( int i = 0; i < str.length; i++ ) {
currentRow.createCell( i )
.setCellValue( str[ i ] );
}
}
DateFormat df = new SimpleDateFormat( "yyyy-mm-dd-HHmmss" );
Date today = Calendar.getInstance()
.getTime();
String reportDate = df.format( today );
FileOutputStream fileOutputStream = new FileOutputStream( xlsxFileAddress );
workBook.write( fileOutputStream );
fileOutputStream.close();
//System.out.println( "Done" );
}
catch ( Exception ex ) {
System.out.println( ex.getMessage() + "Exception in try" );
}
}
public static void convertCsvToXlsx(String xlsLocation, String csvLocation) throws Exception {
SXSSFWorkbook workbook = new SXSSFWorkbook();
SXSSFSheet sheet = workbook.createSheet("Sheet");
AtomicReference<Integer> row = new AtomicReference<>(0);
Files.readAllLines(Paths.get(csvLocation)).forEach(line -> {
Row currentRow = sheet.createRow(row.getAndSet(row.get() + 1));
String[] nextLine = line.split(",");
Stream.iterate(0, i -> i + 1).limit(nextLine.length).forEach(i -> {
currentRow.createCell(i).setCellValue(nextLine[i]);
});
});
FileOutputStream fos = new FileOutputStream(new File(xlsLocation));
workbook.write(fos);
fos.flush();
}
I have found SXSSFWorkbook really faster then XSSFWorkbook. Here is the modified code:
try {
String csvFileInput = "inputFile.csv";
String xlsxFileOutput ="outputFile.xls";
LOGGER.error(csvFileInput);
LOGGER.error( xlsxFileOutput);
SXSSFWorkbook workBook = new SXSSFWorkbook();
Sheet sheet = workBook.createSheet(transformBean.getOutputFileName());
String currentLine = null;
int RowNum = 0;
BufferedReader br = new BufferedReader(new FileReader(csvFileInput));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split(",");
RowNum++;
Row currentRow = sheet.createRow(RowNum);
for (int i = 0; i < str.length; i++) {
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileOutput);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage() + "Found Exception");
}
if(new File(newFileName).isFile()) return;
#SuppressWarnings("resource")
HSSFWorkbook wb = new HSSFWorkbook();
Row xlsRow;
Cell xlsCell;
HSSFSheet sheet = wb.createSheet("sheet1");
int rowIndex = 0;
for(CSVRecord record : CSVFormat.EXCEL.parse(new FileReader(fileName))) {
xlsRow = sheet.createRow(rowIndex);
for(int i = 0; i < record.size(); i ++){
xlsCell = xlsRow.createCell(i);
xlsCell.setCellValue(record.get(i));
}
rowIndex ++;
}
FileOutputStream out = new FileOutputStream(newFileName);
wb.write(out);
out.close();
Try this one if you have inputstream
public static XSSFWorkbook csvToXLSX(InputStream inputStream) throws IOException {
XSSFWorkbook workBook = new XSSFWorkbook();
try(BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
Sheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int rowNum=0;
while ((currentLine = br.readLine()) != null) {
String[] str = currentLine.split(",");
rowNum++;
Row currentRow=sheet.createRow(rowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
log.info("CSV file converted to the workbook");
return workBook;
} catch (Exception ex) {
log.error("Exception while converting csv to xls {}",ex);
}finally {
if (Objects.nonNull(workBook)) {
workBook.close();
}
}
return workBook;
}

Error "Operation not permitted on IsolatedStorageFileStream." wp7

I am trying to read a text file from IsolatedStorage and check it contains a string. If not, the string is added to the end of the file. But When I am trying to write the string into file I got an error: "Operation not permitted on IsolatedStorageFileStream.". My code shown below. How can I overcome this problem?
public void AddToDownloadList()
{
IsolatedStorageFile downloadFile=IsolatedStorageFile.GetUserStoreForApplication();
try
{
string downloads = string.Empty;
if (!downloadFile.DirectoryExists("DownloadedFiles"))
downloadFile.CreateDirectory( "DownloadedFiles" );
if(downloadFile.FileExists("DownloadedFiles\\DownloadList.txt"))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile("DownloadedFiles\\DownloadList.txt",FileMode.Open, FileAccess.Read );
using ( StreamReader reader = new StreamReader( downloadStream ) )
{
downloads = reader.ReadToEnd();
reader.Close();
}
downloadFile.DeleteFile( "DownloadedFiles\\DownloadList.txt" );
}
downloadFile.CreateFile( "DownloadedFiles\\DownloadList.txt" );
string currentFile = FileName;
if ( !downloads.Contains( currentFile ) )
{
downloads += currentFile;
using ( StreamWriter writeFile = new StreamWriter( new IsolatedStorageFileStream( "DownloadedFiles\\DownloadList.txt", FileMode.Create, FileAccess.Write, downloadFile ) ) )
{
writeFile.Write( currentFile + "," );
writeFile.Close();
}
}
}
catch ( Exception ex )
{
string message = ex.Message;
}
}
I think the problem you were having has to do with the line where you create the StreamWriter by newing up the IsolatedStorageFileStream - when you already should have the right one from the return of the downloadFile.CreateFile() call.
Try this code, I think it does what you want to do:
public static void AddToDownloadList()
{
try
{
AddToDownloadList("DownloadedFiles", "this file name", "DownloadedFiles\\DownloadList.txt");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
}
}
public static void AddToDownloadList(string directory, string fileName, string filePath)
{
string downloads = string.Empty;
using (IsolatedStorageFile downloadFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!downloadFile.DirectoryExists(directory))
downloadFile.CreateDirectory(directory);
if (downloadFile.FileExists(filePath))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile(filePath, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(downloadStream))
{
downloads = reader.ReadToEnd();
reader.Close();
}
}
string currentFile = fileName;
if (!downloads.Contains(currentFile))
{
downloadFile.DeleteFile(filePath);
using (IsolatedStorageFileStream stream = downloadFile.CreateFile(filePath))
{
downloads += currentFile;
using (StreamWriter writeFile = new StreamWriter(stream))
{
writeFile.Write(currentFile + ",");
writeFile.Close();
}
}
}
}
}

Windows Phone 7 - Upload file to FTP server

Hy.
I do an application in WP7 which is connet a FTP server. I would like to upload a photo(with photochoosertask).
I wrote a PhotoChooserTask() which I could choose a photo. The program save the photo name(samplephoto01.jpg) and the photo route.
And I wrote a code which send command to FTP server:
public static void Execute(String msg)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
Byte[] cmd = Encoding.UTF8.GetBytes((msg + "\r\n").ToCharArray());
socketEventArg.SetBuffer(cmd, 0, cmd.Length);
socket.SendAsync(socketEventArg);
}
This code i can chose the photo:
public void SelectAndUpLoad()
{
PhotoChooserTask p = new PhotoChooserTask();
p.Completed += new EventHandler<PhotoResult>(pt_Completed);
p.ShowCamera = true;
p.Show();
}
void pt_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage img = new BitmapImage();
img.SetSource(e.ChosenPhoto);
MediaLibrary library = new MediaLibrary();
string PhotoPath = e.OriginalFileName;
// MessageBox.Show(PhotoPath);
for (int i = 0; i < library.Pictures.Count; i++)
{
Stream s = library.Pictures[i].GetImage();
if (s.Length == e.ChosenPhoto.Length)
{
string filename = library.Pictures[i].Name;
MessageBoxResult m = MessageBox.Show(filename, "Upload?", MessageBoxButton.OKCancel);
if (m == MessageBoxResult.OK)
{
Ftp.UploadFile(PhotoPath);
}
else
{
return;
}
break;
}
}
}
}
And this is the code whic i would like to upload the file:
public static void UploadFile(string file)
{
FileStream stream = new FileStream(file, FileMode.Open);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Execute("STRO " + file);
stream.Seek(0, SeekOrigin.Begin);
stream.Close();
}
But when i use the UploadFile(); method the program answer this:
MethodAccessException was unhandled
This code:
.
.
Ftp.UploadFile(PhotoPath);
}
else
{ //MethodAccessException
return;
}
break;
}
What was the wrong? Thank you!
I rewrote this code with IsolatedStorage to this:
for (int i = 0; i < library.Pictures.Count; i++)
{
Stream s = library.Pictures[i].GetImage();
if (s.Length == e.ChosenPhoto.Length)
{
string filename = library.Pictures[i].Name;
MessageBoxResult m = MessageBox.Show(filename, "Upload?", MessageBoxButton.OKCancel);
if (m == MessageBoxResult.OK)
{
IsolatedStorageFile iss = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fs = iss.OpenFile(PhotoPath, FileMode.Open);
Ftp.UploadFile(fs, filename);
fs.Close();
}
else
{
return;
}
break;
}
}
And the UploadFile() method:
public static void UploadFile(IsolatedStorageFileStream file, string RemoteFile)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
int bytes;
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Execute("STRO " + RemoteFile);
file.Seek(0, SeekOrigin.Begin);
while ((bytes = file.Read(buffer, 0, buffer.Length)) > 0)
{
socketEventArg.SetBuffer(buffer, bytes, 0);
socket.SendAsync(socketEventArg);
}
}
But i get an exception in this source:
IsolatedStorageFileStream fs = iss.OpenFile(PhotoPath, FileMode.Open);
The exception is: IsolatedStorageException was unhadnled.
What is wrong?
I think your problem lies in the line:
FileStream stream = new FileStream(file, FileMode.Open);
You can't open files this way on WP7. To get a stream to a file, you can either open it from the Isolated Storage (given that the file is stored there), or use the stream provided by a built-in method.
In your case, you have the stream with the property e.ChosenPhoto. Why don't you use it directly?
public static void UploadFile(Stream stream, string file)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Execute("STRO " + file);
stream.Seek(0, SeekOrigin.Begin);
stream.Close();
}
Then call UploadFile using e.ChosenPhoto as the first argument.

Resources